1
//! Pure scroll state management — the single source of truth for scroll offsets.
2
//!
3
//! # Architecture
4
//!
5
//! `ScrollManager` is the exclusive owner of all scroll state. Other modules
6
//! interact with scrolling only through its public API:
7
//!
8
//! - **Platform shell** (macos/events.rs, etc.): Calls `record_scroll_from_hit_test()` to queue
9
//!   trackpad/mouse wheel input for the physics timer.
10
//! - **Scroll physics timer** (`scroll_timer.rs)`: Consumes inputs via `ScrollInputQueue`, applies
11
//!   physics, and pushes `CallbackChange::ScrollTo` for each updated node.
12
//! - **Event processing** (`event_v2.rs)`: Processes `ScrollTo` changes, sets scroll positions, and
13
//!   checks `VirtualView` re-invocation transparently.
14
//! - **Drag autoscroll** (`shell2/common/event.rs`): while a text-selection drag is held past a
15
//!   container's edge, a 60Hz timer pushes `CallbackChange::ScrollTo`. It does NOT go through the
16
//!   gesture manager — an earlier `AutoScrollDirection` design did, and was documented here long
17
//!   after it stopped being constructed anywhere.
18
//! - **Render loop**: Calls `tick()` every frame to advance easing animations.
19
//! - **`WebRender` sync** (`wr_translate2.rs)`: Reads offsets via `get_scroll_states_for_dom()` to
20
//!   synchronize scroll frames.
21
//! - **Layout** (cache.rs): Registers scroll nodes via `register_or_update_scroll_node()` after
22
//!   layout completes.
23
//!
24
//! # Scroll Flow
25
//!
26
//! ```text
27
//! Platform Event Handler
28
//!   → record_scroll_from_hit_test() → ScrollInputQueue
29
//!   → starts SCROLL_MOMENTUM_TIMER_ID if not running
30
//!
31
//! Timer fires (every ~16ms):
32
//!   → queue.take_all() → physics integration
33
//!   → push_change(CallbackChange::ScrollTo)
34
//!
35
//! ScrollTo processing (event_v2.rs):
36
//!   → scroll_manager.set_scroll_position()
37
//!   → virtual_view_manager.check_reinvoke() (transparent VirtualView support)
38
//!   → repaint
39
//! ```
40
//!
41
//! This module provides:
42
//! - Smooth scroll animations with easing
43
//! - Event source classification for scroll events
44
//! - Scrollbar geometry and hit-testing
45
//! - Virtual scroll bounds for `VirtualView` nodes
46

            
47
use alloc::collections::BTreeMap;
48
#[cfg(feature = "std")]
49
use alloc::vec::Vec;
50
#[cfg(feature = "std")]
51
use std::sync::{Arc, Mutex};
52

            
53
use azul_core::{
54
    dom::{DomId, DomNodeId, NodeId, ScrollbarOrientation},
55
    events::{EasingFunction, EventData, EventType, SyntheticEvent},
56
    geom::{LogicalPosition, LogicalRect, LogicalSize},
57
    hit_test::ScrollPosition,
58
    spaces::Inclusivity,
59
    styled_dom::NodeHierarchyItemId,
60
    task::{Duration, Instant},
61
};
62
use azul_css::{impl_option, impl_option_inner};
63

            
64
use crate::{
65
    managers::hover::InputPointId,
66
    solver3::{layout_tree::LayoutNodeId, scrollbar::compute_scrollbar_geometry_with_button_size},
67
};
68

            
69
/// Minimum change in scroll offset (in logical pixels) to consider the position
70
/// "actually moved" and mark the scroll state dirty.
71
const SCROLL_CHANGE_EPSILON: f32 = 0.01;
72

            
73
// ============================================================================
74
// Scroll Input Types (for timer-based physics architecture)
75
// ============================================================================
76

            
77
/// Classifies the source of a scroll input event.
78
///
79
/// This determines how the scroll physics timer processes the input:
80
/// - `TrackpadContinuous`: The OS already applies momentum — set position directly
81
/// - `WheelDiscrete`: Mouse wheel clicks — apply as impulse with momentum decay
82
/// - `Programmatic`: API-driven scroll — apply with optional easing animation
83
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84
pub enum ScrollInputSource {
85
    /// Continuous trackpad gesture (macOS precise scrolling).
86
    /// Position is set directly — the OS handles momentum/physics.
87
    TrackpadContinuous,
88
    /// The OS momentum tail after the fingers lifted (macOS
89
    /// `momentumPhase == Began | Changed`).
90
    ///
91
    /// Moves the content like
92
    /// `TrackpadContinuous` while the node is in range; the first delta that
93
    /// pushes past an edge hands the axis to the rubber-band spring (with the
94
    /// delta's velocity as the bump) and every later momentum delta on that
95
    /// node is dropped — the OS momentum knows nothing about our edge, and a
96
    /// spring it kept interrupting was never seen by the user.
97
    TrackpadMomentum,
98
    /// Trackpad gesture ended (fingers lifted off trackpad).
99
    /// Triggers spring-back if the scroll position is past the bounds
100
    /// (rubber-banding overshoot). The OS sends this when
101
    /// `NSEventPhaseEnded` or momentumPhaseEnded is detected.
102
    TrackpadEnd,
103
    /// Discrete mouse wheel steps (Windows/Linux mouse wheel).
104
    /// Applied as velocity impulse with momentum decay.
105
    WheelDiscrete,
106
    /// Programmatic scroll (scrollTo API, keyboard Page Up/Down).
107
    /// Applied with optional easing animation.
108
    Programmatic,
109
    /// Animated scroll toward an ABSOLUTE target offset (`delta` carries
110
    /// the target, not a delta): the physics timer seeks it with a
111
    /// critically-damped spring, so scroll-to-caret / scroll-to-page /
112
    /// find-result navigation glide instead of jumping, and a retarget
113
    /// mid-flight keeps the current velocity (no restart). Produced by
114
    /// `LayoutWindow::scroll_to_animated`.
115
    AnimateTo,
116
}
117

            
118
/// WHERE a scroll input physically came from - distinct from
119
/// [`ScrollInputSource`], which is the PROCESSING model. Different devices
120
/// deserve different curves (a wheel step animated with the trackpad's
121
/// long spring feels jarring), and accessibility drivers / test harnesses
122
/// need to identify themselves for correct treatment and diagnostics.
123
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
124
pub enum ScrollInputDevice {
125
    /// Discrete physical mouse wheel clicks.
126
    MouseWheel,
127
    /// Trackpad / precision touchpad gestures.
128
    Touchpad,
129
    /// Direct touchscreen panning.
130
    Touchscreen,
131
    /// Keyboard navigation (PageUp/PageDown/arrows/Home/End).
132
    Keyboard,
133
    /// Assistive technology (screen readers, switch access).
134
    Accessibility,
135
    /// An automated test driver (e2e harness, CI scenarios).
136
    TestDriver,
137
    /// API-driven (`scroll_to` / `scroll_to_animated` from app code).
138
    Programmatic,
139
    /// Origin unknown (legacy producers). Treated like `MouseWheel` for
140
    /// curve selection on discrete inputs.
141
    #[default]
142
    Unknown,
143
}
144

            
145
/// A single scroll input event to be processed by the physics timer.
146
///
147
/// Scroll inputs are recorded by the platform event handler and consumed
148
/// by the scroll physics timer callback. This decouples input recording
149
/// from physics simulation.
150
#[derive(Debug, Clone)]
151
pub struct ScrollInput {
152
    /// DOM containing the scrollable node
153
    pub dom_id: DomId,
154
    /// Target scroll node
155
    pub node_id: NodeId,
156
    /// Scroll delta (positive = scroll down/right)
157
    pub delta: LogicalPosition,
158
    /// When this input was recorded
159
    pub timestamp: Instant,
160
    /// How this input should be processed
161
    pub source: ScrollInputSource,
162
    /// Where this input physically came from (curve selection,
163
    /// accessibility, diagnostics).
164
    pub device: ScrollInputDevice,
165
}
166

            
167
/// Thread-safe queue for scroll inputs, shared between event handlers and timer callbacks.
168
///
169
/// Event handlers push inputs, the physics timer pops them. Protected by a Mutex
170
/// so that the timer callback (which only has `&CallbackInfo` / `*const LayoutWindow`)
171
/// can still consume pending inputs without needing `&mut`.
172
#[cfg(feature = "std")]
173
#[derive(Debug, Clone, Default)]
174
pub struct ScrollInputQueue {
175
    inner: Arc<Mutex<Vec<ScrollInput>>>,
176
}
177

            
178
#[cfg(feature = "std")]
179
impl ScrollInputQueue {
180
    #[must_use]
181
49
    pub fn new() -> Self {
182
49
        Self {
183
49
            inner: Arc::new(Mutex::new(Vec::new())),
184
49
        }
185
49
    }
186

            
187
    /// Push a new scroll input (called from platform event handler)
188
1905
    pub fn push(&self, input: ScrollInput) {
189
1905
        if let Ok(mut queue) = self.inner.lock() {
190
1905
            queue.push(input);
191
1905
        }
192
1905
    }
193

            
194
    /// Take all pending inputs (called from timer callback)
195
    #[must_use]
196
25
    pub fn take_all(&self) -> Vec<ScrollInput> {
197
25
        self.inner
198
25
            .lock()
199
25
            .map_or_else(|_| Vec::new(), |mut queue| core::mem::take(&mut *queue))
200
25
    }
201

            
202
    /// Take at most `max_events` recent inputs, sorted by timestamp (newest last).
203
    /// Any older events beyond `max_events` are discarded.
204
    /// This prevents the physics timer from processing an unbounded backlog.
205
    #[must_use]
206
2246
    pub fn take_recent(&self, max_events: usize) -> Vec<ScrollInput> {
207
2246
        self.inner.lock().map_or_else(
208
            |_| Vec::new(),
209
2246
            |mut queue| {
210
2246
                let mut events = core::mem::take(&mut *queue);
211
2246
                if events.len() > max_events {
212
                    // Sort by timestamp ascending (oldest first), keep last N
213
1503
                    events.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
214
4
                    events.drain(..events.len() - max_events);
215
2242
                }
216
2246
                events
217
2246
            },
218
        )
219
2246
    }
220

            
221
    /// Check if there are pending inputs without consuming them
222
    #[must_use]
223
2374
    pub fn has_pending(&self) -> bool {
224
2374
        self.inner.lock().map(|q| !q.is_empty()).unwrap_or(false)
225
2374
    }
226
}
227

            
228
// Scrollbar Component Types
229

            
230
/// Which component of a scrollbar was hit during hit-testing
231
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
232
pub enum ScrollbarComponent {
233
    /// The track (background) of the scrollbar
234
    Track,
235
    /// The draggable thumb (indicator of current scroll position)
236
    Thumb,
237
    /// Top/left button (scrolls by one page up/left)
238
    TopButton,
239
    /// Bottom/right button (scrolls by one page down/right)
240
    BottomButton,
241
}
242

            
243
/// Scrollbar geometry state (calculated per frame, used for hit-testing and rendering)
244
#[derive(Copy, Debug, Clone)]
245
pub struct ScrollbarState {
246
    /// Is this scrollbar visible? (content larger than container)
247
    pub visible: bool,
248
    /// Orientation
249
    pub orientation: ScrollbarOrientation,
250
    /// Base size (1:1 square, width = height). This is the unscaled size.
251
    pub base_size: f32,
252
    /// Scale transform to apply (calculated from container size)
253
    pub scale: LogicalPosition, // x = width scale, y = height scale
254
    /// Thumb position ratio (0.0 = top/left, 1.0 = bottom/right)
255
    pub thumb_position_ratio: f32,
256
    /// Thumb size ratio (0.0 = invisible, 1.0 = entire track)
257
    pub thumb_size_ratio: f32,
258
    /// Position of the scrollbar in the container (for hit-testing)
259
    pub track_rect: LogicalRect,
260
    /// Button size (square: `button_size` × `button_size`)
261
    pub button_size: f32,
262
    /// Usable track length after subtracting buttons
263
    pub usable_track_length: f32,
264
    /// Thumb length in pixels
265
    pub thumb_length: f32,
266
    /// Thumb offset from start of usable track region
267
    pub thumb_offset: f32,
268
}
269

            
270
impl ScrollbarState {
271
    /// Determine which component was hit at the given local position (relative to `track_rect`
272
    /// origin). Uses the shared geometry values (`button_size`, `usable_track_length`,
273
    /// `thumb_length`, `thumb_offset`) for consistent hit-testing.
274
    #[must_use]
275
37
    pub fn hit_test_component(&self, local_pos: LogicalPosition) -> ScrollbarComponent {
276
37
        match self.orientation {
277
            ScrollbarOrientation::Vertical => {
278
                // Top button
279
30
                if local_pos.y < self.button_size {
280
7
                    return ScrollbarComponent::TopButton;
281
23
                }
282

            
283
                // Bottom button
284
23
                let track_height = self.track_rect.size.height;
285
23
                if local_pos.y > track_height - self.button_size {
286
4
                    return ScrollbarComponent::BottomButton;
287
19
                }
288

            
289
                // Thumb region starts after top button
290
19
                let thumb_y_start = self.button_size + self.thumb_offset;
291
19
                let thumb_y_end = thumb_y_start + self.thumb_length;
292

            
293
19
                if local_pos.y >= thumb_y_start && local_pos.y <= thumb_y_end {
294
11
                    ScrollbarComponent::Thumb
295
                } else {
296
8
                    ScrollbarComponent::Track
297
                }
298
            }
299
            ScrollbarOrientation::Horizontal => {
300
                // Left button
301
7
                if local_pos.x < self.button_size {
302
                    return ScrollbarComponent::TopButton;
303
7
                }
304

            
305
                // Right button
306
7
                let track_width = self.track_rect.size.width;
307
7
                if local_pos.x > track_width - self.button_size {
308
                    return ScrollbarComponent::BottomButton;
309
7
                }
310

            
311
                // Thumb region starts after left button
312
7
                let thumb_x_start = self.button_size + self.thumb_offset;
313
7
                let thumb_x_end = thumb_x_start + self.thumb_length;
314

            
315
7
                if local_pos.x >= thumb_x_start && local_pos.x <= thumb_x_end {
316
6
                    ScrollbarComponent::Thumb
317
                } else {
318
1
                    ScrollbarComponent::Track
319
                }
320
            }
321
        }
322
37
    }
323
}
324

            
325
/// Result of a scrollbar hit-test
326
///
327
/// Contains information about which scrollbar component was hit
328
/// and the position relative to both the track and the window.
329
#[derive(Debug, Clone, Copy)]
330
pub struct ScrollbarHit {
331
    /// DOM containing the scrollable node
332
    pub dom_id: DomId,
333
    /// Node with the scrollbar
334
    pub node_id: NodeId,
335
    /// Whether this is a vertical or horizontal scrollbar
336
    pub orientation: ScrollbarOrientation,
337
    /// Which component was hit (track, thumb, buttons)
338
    pub component: ScrollbarComponent,
339
    /// Position relative to `track_rect` origin
340
    pub local_position: LogicalPosition,
341
    /// Original global window position
342
    pub global_position: LogicalPosition,
343
}
344

            
345
/// One end of a scroll gesture, recorded by [`ScrollManager::note_scroll_phase`]
346
/// and drained as a `ScrollStart` / `ScrollEnd` event.
347
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348
pub enum ScrollPhaseTransition {
349
    /// A gesture began: the first input after a quiet period.
350
    Started,
351
    /// A gesture ended: the finger lifted and any momentum tail finished.
352
    Ended,
353
}
354

            
355
// Core Scroll Manager
356

            
357
/// Manages all scroll state and animations for a window
358
#[derive(Debug, Clone, Default)]
359
// The bools are INDEPENDENT latches (per-axis / per-phase arming state), not the
360
// states of one machine; folding them into enums would make legal combinations
361
// unrepresentable.
362
#[allow(clippy::struct_excessive_bools)]
363
pub struct ScrollManager {
364
    /// Maps (`DomId`, `NodeId`) to their scroll state
365
    states: BTreeMap<(DomId, NodeId), AnimatedScrollState>,
366
    /// Scrollbar geometry states (calculated per frame)
367
    scrollbar_states: BTreeMap<(DomId, NodeId, ScrollbarOrientation), ScrollbarState>,
368
    /// Thread-safe queue for scroll inputs (shared with timer callbacks)
369
    #[cfg(feature = "std")]
370
    pub scroll_input_queue: ScrollInputQueue,
371
    /// Raw wheel/trackpad delta recorded *this input pass*, regardless of whether
372
    /// a scrollable node was under the cursor. The scroll input queue only carries
373
    /// deltas destined for scrollable containers (consumed by the physics timer);
374
    /// this field additionally lets `determine_all_events` synthesize a `Scroll`
375
    /// event aimed at the hovered node so non-scroll-container widgets (e.g. the
376
    /// map, which treats wheel = zoom) can react via a `HoverEventFilter::Scroll`
377
    /// callback + `CallbackInfo::get_scroll_delta`. Set in
378
    /// [`Self::record_scroll_from_hit_test`]; read during event determination and
379
    /// callback dispatch, then cleared at the end of the pass.
380
    pub pending_wheel_event: Option<LogicalPosition>,
381
    /// Which pointer seat the pending wheel delta came from (9b-ii-b); the
382
    /// `Scroll` event is aimed at THAT seat's hovered node. `Default` (0) is
383
    /// the primary.
384
    pub pending_wheel_seat: u64,
385
    /// Set when a scroll position changes; cleared after the display list
386
    /// is regenerated.  Used by the CPU renderer path to detect when the
387
    /// display list must be rebuilt even though the DOM hasn't changed.
388
    scroll_dirty: bool,
389
    /// Scroll-direction preference, applied ONCE in [`Self::record_scroll_input`]
390
    /// (the single chokepoint every platform's wheel/axis event flows through).
391
    ///
392
    /// `false` (default) = traditional desktop wheel: a raw "scroll down" event
393
    /// increases the offset (content moves up). `true` = natural: inverted.
394
    /// Replaces the per-platform hardcoded `-delta` negations so the sign lives
395
    /// in one configurable place ([`Self::set_natural_scroll`]).
396
    ///
397
    /// CAVEAT: on macOS and on Linux touchpads via libinput the OS/driver ALREADY
398
    /// applies the user's natural-scroll preference before azul sees the delta, so
399
    /// this flag must stay at its default there (we preserve current behavior) and
400
    /// primarily controls mouse-wheel direction on platforms that don't pre-apply.
401
    natural_scroll: bool,
402
    /// Whether the pointing device's scroll motion is inverted relative to
403
    /// the surface — "natural scrolling". Set by the backends that report it
404
    /// (macOS `isDirectionInvertedFromDevice`, Wayland
405
    /// `axis_relative_direction`); false where the platform does not say.
406
    ///
407
    /// The deltas have ALREADY had the preference applied by the OS, so this
408
    /// is not used to transform them. It is for a client that needs motion in
409
    /// device terms rather than page terms.
410
    pub scroll_direction_inverted: bool,
411
    /// Scroll-gesture phase latch, for `ScrollStart` / `ScrollEnd`.
412
    ///
413
    /// `true` between the first input of a gesture and the input that ends
414
    /// it. The engine has always known the phase — `ScrollInputSource`
415
    /// distinguishes `TrackpadContinuous`, `TrackpadMomentum`, `TrackpadEnd`
416
    /// and `WheelDiscrete`, and macOS derives all four from `NSEvent.phase` /
417
    /// `momentumPhase` — but it never became an app-visible event, so the
418
    /// `ScrollStart` / `ScrollEnd` filters could not fire. Latching here
419
    /// rather than in the shells keeps the four backends agreeing on one
420
    /// definition of "a gesture".
421
    pub scroll_gesture_active: bool,
422
    /// Phase transitions observed since the last drain, oldest first. Drained
423
    /// by `EventProvider::get_pending_events`.
424
    pub pending_scroll_phase: Vec<ScrollPhaseTransition>,
425
}
426

            
427
/// The complete scroll state for a single node (with animation support)
428
#[derive(Debug, Clone)]
429
pub struct AnimatedScrollState {
430
    /// Current scroll offset (live, may be animating)
431
    pub current_offset: LogicalPosition,
432
    /// Ongoing smooth scroll animation, if any
433
    pub animation: Option<ScrollAnimation>,
434
    /// Last time scroll activity occurred (for fading scrollbars)
435
    pub last_activity: Instant,
436
    /// Bounds of the scrollable container
437
    pub container_rect: LogicalRect,
438
    /// Bounds of the total content (for calculating scroll limits)
439
    pub content_rect: LogicalRect,
440
    /// Virtual scroll size from `VirtualView` callback (if this node hosts a `VirtualView`).
441
    /// When set, clamp logic uses this instead of `content_rect` for max scroll bounds.
442
    pub virtual_scroll_size: Option<LogicalSize>,
443
    /// Virtual scroll offset from `VirtualView` callback
444
    pub virtual_scroll_offset: Option<LogicalPosition>,
445
    /// Per-node overscroll behavior for X axis (from CSS `overscroll-behavior-x`)
446
    pub overscroll_behavior_x: azul_css::props::style::scrollbar::OverscrollBehavior,
447
    /// Per-node overscroll behavior for Y axis (from CSS `overscroll-behavior-y`)
448
    pub overscroll_behavior_y: azul_css::props::style::scrollbar::OverscrollBehavior,
449
    /// Per-node overflow scrolling mode (from CSS `-azul-overflow-scrolling`)
450
    pub overflow_scrolling: azul_css::props::style::scrollbar::OverflowScrolling,
451
    /// CSS-resolved scrollbar thickness (from `scrollbar-width` property).
452
    /// Used for rendering and hit-testing. Defaults to 16.0 if not set.
453
    pub scrollbar_thickness: f32,
454
    /// Visual rendering width in CSS pixels (e.g. 8.0 for thin overlay).
455
    /// Non-zero even for overlay scrollbars. Falls back to `scrollbar_thickness` if 0.
456
    pub visual_width_px: f32,
457
    /// Whether this node also needs a horizontal scrollbar (affects vertical geometry)
458
    pub has_horizontal_scrollbar: bool,
459
    /// Whether this node also needs a vertical scrollbar (affects horizontal geometry)
460
    pub has_vertical_scrollbar: bool,
461
}
462

            
463
/// Details of an in-progress smooth scroll animation.
464
///
465
/// `pub` because `ScrollState::animation` is already a `pub` field holding it —
466
/// a private type behind a public field is only an error at the point somebody
467
/// outside this module reads it, which is why this compiled until the E2E
468
/// manager fingerprints needed to ask "is a scroll animation in flight?".
469
#[derive(Debug, Clone)]
470
pub struct ScrollAnimation {
471
    /// When the animation started
472
    start_time: Instant,
473
    /// Total duration of the animation
474
    duration: Duration,
475
    /// Scroll offset at animation start
476
    start_offset: LogicalPosition,
477
    /// Target scroll offset at animation end
478
    target_offset: LogicalPosition,
479
    /// Easing function for interpolation
480
    easing: EasingFunction,
481
}
482

            
483
/// Read-only snapshot of a scroll node's state, returned by `CallbackInfo` queries.
484
///
485
/// Provides all the information a timer callback needs to compute scroll physics
486
/// without requiring mutable access to the `ScrollManager`.
487
/// `#[repr(C)]` because this is returned THROUGH the C API by
488
/// `CallbackInfo::get_scroll_node_info` - without it the layout is undefined
489
/// across the boundary and the generated bindings read garbage fields.
490
#[derive(Copy, Debug, Clone, PartialEq)]
491
#[repr(C)]
492
pub struct ScrollNodeInfo {
493
    /// Current scroll offset
494
    pub current_offset: LogicalPosition,
495
    /// Container (viewport) bounds
496
    pub container_rect: LogicalRect,
497
    /// Content bounds (total scrollable area)
498
    pub content_rect: LogicalRect,
499
    /// Maximum scroll in X direction
500
    pub max_scroll_x: f32,
501
    /// Maximum scroll in Y direction
502
    pub max_scroll_y: f32,
503
    /// Per-node overscroll behavior for X axis
504
    pub overscroll_behavior_x: azul_css::props::style::scrollbar::OverscrollBehavior,
505
    /// Per-node overscroll behavior for Y axis
506
    pub overscroll_behavior_y: azul_css::props::style::scrollbar::OverscrollBehavior,
507
    /// Per-node overflow scrolling mode (auto vs touch)
508
    pub overflow_scrolling: azul_css::props::style::scrollbar::OverflowScrolling,
509
}
510

            
511
azul_css::impl_option!(
512
    ScrollNodeInfo,
513
    OptionScrollNodeInfo,
514
    copy = false,
515
    [Debug, Copy, Clone, PartialEq]
516
);
517

            
518
/// Result of a scroll tick, indicating what actions are needed
519
#[derive(Debug, Default)]
520
pub struct ScrollTickResult {
521
    /// If true, a repaint is needed (scroll offset changed)
522
    pub needs_repaint: bool,
523
    /// Nodes whose scroll position was updated this tick
524
    pub updated_nodes: Vec<(DomId, NodeId)>,
525
}
526

            
527
// ScrollManager Implementation
528

            
529
impl ScrollManager {
530
    /// Creates a new empty `ScrollManager`
531
    #[must_use]
532
9200
    pub fn new() -> Self {
533
        // `AppConfig::natural_scroll` (9b-ii-b-i-a): `Enabled` flips in the
534
        // engine; `System` and `Disabled` do not - the platform already
535
        // applied the user's preference to the deltas it hands over, and
536
        // `System` only makes that preference readable.
537
9200
        let mut m = Self {
538
9200
            natural_scroll: matches!(
539
9200
                crate::window::natural_scroll_mode(),
540
                azul_core::resources::NaturalScroll::Enabled
541
            ),
542
9200
            ..Self::default()
543
        };
544
        // Power-user / test override: this env var wins so the direction can
545
        // be flipped without a rebuild and so tests are hermetic.
546
        #[cfg(feature = "std")]
547
9200
        if let Some(v) = std::env::var_os("AZ_NATURAL_SCROLL") {
548
            m.natural_scroll = matches!(v.to_str(), Some("1" | "true" | "TRUE"));
549
9200
        }
550
9200
        m
551
9200
    }
552

            
553
    /// The platform's natural-scrolling preference, where a backend reported
554
    /// one (9b-ii-b-i-a): what `AppConfig::natural_scroll = System` reads.
555
    /// `None` = the platform said nothing (X11, mobile, or no reader yet).
556
    #[must_use]
557
    pub fn system_natural_scroll(&self) -> Option<bool> {
558
        crate::window::system_natural_scroll()
559
    }
560

            
561
    /// Set the scroll-direction preference. `true` = natural (content follows the
562
    /// gesture / inverted from the traditional wheel). Platform shells call this
563
    /// from the detected OS preference. See the `natural_scroll` field docs for the
564
    /// macOS/libinput pre-application caveat.
565
5
    pub const fn set_natural_scroll(&mut self, natural: bool) {
566
5
        self.natural_scroll = natural;
567
5
    }
568

            
569
    /// Current scroll-direction preference (`true` = natural/inverted).
570
    #[must_use]
571
4
    pub const fn is_natural_scroll(&self) -> bool {
572
4
        self.natural_scroll
573
4
    }
574

            
575
    /// The sign applied to a raw input delta to get the offset delta:
576
    /// `-1.0` traditional (default), `+1.0` natural. Centralises what used to be a
577
    /// hardcoded `-delta` at every platform call site.
578
    #[inline]
579
27
    const fn scroll_sign(&self) -> f32 {
580
27
        if self.natural_scroll {
581
3
            1.0
582
        } else {
583
24
            -1.0
584
        }
585
27
    }
586

            
587
    /// Sizes of the internal maps — used by `AZ_E2E_TEST` to watch for
588
    /// unbounded growth across resize/tick iterations.
589
    #[must_use]
590
12
    pub fn debug_counts(&self) -> (usize, usize) {
591
12
        (self.states.len(), self.scrollbar_states.len())
592
12
    }
593

            
594
    /// Returns `true` if any scroll position changed since the last
595
    /// `clear_scroll_dirty()` call.
596
36
    pub(crate) const fn has_pending_scroll_changes(&self) -> bool {
597
36
        self.scroll_dirty
598
36
    }
599

            
600
    /// Every `(DomId, NodeId)` this manager currently keys scroll state on.
601
    ///
602
    /// The E2E `assert_manager_invariants` op needs the KEY SET, not just the
603
    /// count `debug_counts()` reports: a key naming a node that no longer exists
604
    /// in `layout_results` is a dangling index (invariant X10), and a key set is
605
    /// the only way to see it from outside.
606
    #[must_use]
607
19494
    pub fn state_keys(&self) -> Vec<(DomId, NodeId)> {
608
19494
        self.states.keys().copied().collect()
609
19494
    }
610

            
611
    /// Every `(DomId, NodeId)` whose `AnimatedScrollState` currently carries an
612
    /// easing animation. `has_active_animations()` is exactly
613
    /// `!animating_keys().is_empty()`; E2E invariant X2 asserts that identity.
614
    #[must_use]
615
19
    pub fn animating_keys(&self) -> Vec<(DomId, NodeId)> {
616
19
        self.states
617
19
            .iter()
618
19
            .filter(|(_, s)| s.animation.is_some())
619
19
            .map(|(k, _)| *k)
620
19
            .collect()
621
19
    }
622

            
623
    /// Clear the dirty flag after the display list has been regenerated.
624
8454
    pub const fn clear_scroll_dirty(&mut self) {
625
8454
        self.scroll_dirty = false;
626
8454
    }
627

            
628
    /// Build a map from `scroll_id` (`LocalScrollId`) to current scroll offset.
629
    ///
630
    /// Used by the CPU renderer to look up scroll positions at render time
631
    /// without embedding them in the display list.
632
    ///
633
    /// Takes `DomLayoutResult::scroll_id_to_node_id` — the SAME table the
634
    /// `WebRender` path resolves through (`wr_translate2::scroll_all_nodes`) —
635
    /// because it is keyed the way this manager is keyed: by DOM `NodeId`.
636
    ///
637
    /// It used to take the sibling table `scroll_ids` (layout-tree index →
638
    /// `scroll_id`) and index it with `node_id.index()`, i.e. it assumed the
639
    /// layout tree and the DOM share an index space. They do not: anonymous
640
    /// boxes and box splits are inserted during layout-tree construction, so
641
    /// any scroll container with a text sibling ahead of it sits at a
642
    /// different index. The lookup then missed, the container never appeared
643
    /// in this map, the compositor resolved its layer offset as `(0.0, 0.0)`
644
    /// and the content stayed frozen — while the scrollbar thumb, driven by
645
    /// the `(DomId, NodeId)`-keyed GPU value cache, kept tracking the wheel.
646
    #[must_use]
647
16880
    pub fn build_scroll_offset_map(
648
16880
        &self,
649
16880
        dom_id: DomId,
650
16880
        scroll_id_to_node_id: &std::collections::HashMap<u64, NodeId>,
651
16880
    ) -> std::collections::HashMap<u64, (f32, f32)> {
652
16880
        let mut map = std::collections::HashMap::new();
653
33366
        for (&scroll_id, &node_id) in scroll_id_to_node_id {
654
16486
            if let Some(state) = self.states.get(&(dom_id, node_id)) {
655
16457
                map.insert(scroll_id, (state.current_offset.x, state.current_offset.y));
656
16457
            }
657
        }
658
16880
        map
659
16880
    }
660

            
661
    // ========================================================================
662
    // Input Recording API (timer-based architecture)
663
    // ========================================================================
664

            
665
    /// Records a scroll input event into the shared queue.
666
    ///
667
    /// This is the primary entry point for platform event handlers. Instead of
668
    /// directly modifying scroll positions, the input is queued for the scroll
669
    /// physics timer to process. This decouples input from physics simulation.
670
    ///
671
    /// The scroll-direction sign ([`Self::scroll_sign`]) is applied HERE — the
672
    /// single chokepoint every wheel/axis event flows through — so platform shells
673
    /// pass the RAW delta and no longer hardcode `-delta` at each call site.
674
    ///
675
    /// Returns `true` if the physics timer should be started (i.e., there are
676
    /// now pending inputs and no timer is running yet).
677
    #[cfg(feature = "std")]
678
16
    pub fn record_scroll_input(&mut self, mut input: ScrollInput) -> bool {
679
16
        let sign = self.scroll_sign();
680
16
        input.delta.x *= sign;
681
16
        input.delta.y *= sign;
682
16
        let was_empty = !self.scroll_input_queue.has_pending();
683
16
        self.scroll_input_queue.push(input);
684
16
        was_empty // caller should start timer if this returns true
685
16
    }
686

            
687
    /// High-level entry point for platform event handlers: performs hit-test lookup
688
    /// and queues the input for the physics timer, instead of directly modifying offsets.
689
    ///
690
    /// Returns `Some((dom_id, node_id, should_start_timer))` if a scrollable node was found.
691
    /// The caller should start `SCROLL_MOMENTUM_TIMER_ID` when `should_start_timer` is true.
692
    #[cfg(feature = "std")]
693
7
    pub fn record_scroll_from_hit_test(
694
7
        &mut self,
695
7
        delta_x: f32,
696
7
        delta_y: f32,
697
7
        source: ScrollInputSource,
698
7
        device: ScrollInputDevice,
699
7
        hover_manager: &crate::managers::hover::HoverManager,
700
7
        input_point_id: &InputPointId,
701
7
        now: Instant,
702
7
    ) -> Option<(DomId, NodeId, bool)> {
703
        // Fold the source into the gesture latch. Every backend funnels its
704
        // scroll here with an already-classified `source`, so one call covers
705
        // macOS, Wayland, X11 and Win32 — and they cannot drift apart on what
706
        // counts as the start or end of a gesture, which is the whole reason
707
        // the latch lives on the manager rather than in the shells.
708
7
        self.note_scroll_phase(source);
709

            
710
        // Record the raw wheel delta for this pass unconditionally — even when the
711
        // cursor isn't over a scroll container — so a `Scroll` event can be aimed
712
        // at the hovered node (wheel-as-zoom widgets like the map rely on this).
713
7
        self.pending_wheel_event = Some(LogicalPosition {
714
7
            x: delta_x,
715
7
            y: delta_y,
716
7
        });
717
7
        self.pending_wheel_seat = match input_point_id {
718
            InputPointId::Seat(id) => *id,
719
7
            _ => azul_core::window::PRIMARY_POINTER_SEAT,
720
        };
721

            
722
7
        let hit_test = hover_manager.get_current(input_point_id)?;
723

            
724
        // MWA-B2: nested scroll containers — innermost-first with boundary
725
        // handoff. The previous ascending iteration always picked the
726
        // OUTERMOST scrollable ancestor (BTreeMap keys ascend; ancestors
727
        // have lower arena NodeIds), so wheeling over a list inside a
728
        // scrollable page scrolled the page instead of the list. We now
729
        // walk innermost-first and give the event to the first candidate
730
        // that can still move in the delta's direction (the web's default
731
        // overscroll handoff); when every candidate is pinned, the
732
        // innermost scrollable wins so the gesture still targets the node
733
        // under the pointer.
734
6
        let sign = self.scroll_sign();
735
6
        let (eff_x, eff_y) = (delta_x * sign, delta_y * sign);
736
6
        let target = self.select_scroll_target(
737
6
            hit_test
738
6
                .hovered_nodes
739
6
                .iter()
740
6
                .flat_map(|(dom_id, hit_node)| {
741
6
                    hit_node
742
6
                        .scroll_hit_test_nodes
743
6
                        .keys()
744
6
                        .rev()
745
6
                        .map(move |node_id| (*dom_id, *node_id))
746
6
                }),
747
6
            eff_x,
748
6
            eff_y,
749
        );
750
6
        let (dom_id, node_id) = target?;
751
5
        let (delta_x, delta_y) =
752
5
            self.map_wheel_onto_the_only_scrollable_axis(dom_id, node_id, delta_x, delta_y);
753
5
        let input = ScrollInput {
754
5
            dom_id,
755
5
            node_id,
756
5
            // Raw delta — record_scroll_input applies scroll_sign() itself.
757
5
            delta: LogicalPosition {
758
5
                x: delta_x,
759
5
                y: delta_y,
760
5
            },
761
5
            timestamp: now,
762
5
            source,
763
5
            device,
764
5
        };
765
5
        let should_start_timer = self.record_scroll_input(input);
766
5
        Some((dom_id, node_id, should_start_timer))
767
7
    }
768

            
769
    /// MWA-B2: choose the scroll node a wheel/trackpad event should drive.
770
    ///
771
    /// `candidates` must be ordered innermost-first; `eff_x`/`eff_y` are the
772
    /// direction-normalized deltas (post `scroll_sign()`: positive = offset
773
    /// grows = view moves toward content's down/right). The first candidate
774
    /// with remaining travel in a moved direction wins; if every candidate
775
    /// is pinned, the innermost scrollable is returned so the gesture still
776
    /// anchors under the pointer (matches CSS default overscroll behavior).
777
15
    fn select_scroll_target<I>(
778
15
        &self,
779
15
        candidates: I,
780
15
        eff_x: f32,
781
15
        eff_y: f32,
782
15
    ) -> Option<(DomId, NodeId)>
783
15
    where
784
15
        I: Iterator<Item = (DomId, NodeId)>,
785
    {
786
15
        let mut fallback = None;
787
26
        for (dom_id, node_id) in candidates {
788
19
            if !self.is_node_scrollable(dom_id, node_id) {
789
3
                continue;
790
16
            }
791
16
            if fallback.is_none() {
792
12
                fallback = Some((dom_id, node_id));
793
12
            }
794
16
            if self.can_consume_delta(dom_id, node_id, eff_x, eff_y) {
795
8
                return Some((dom_id, node_id));
796
8
            }
797
        }
798
7
        fallback
799
15
    }
800

            
801
    /// A vertical wheel over a box that can ONLY scroll horizontally moves it
802
    /// horizontally.
803
    ///
804
    /// Every browser does this, and without it a horizontal strip — a page
805
    /// rail, a tab bar, a filmstrip — is simply dead to the normal gesture. A
806
    /// mouse wheel has no horizontal axis at all, and on a Mac trackpad a
807
    /// genuine horizontal swipe is frequently claimed by the system for
808
    /// back/forward navigation, so the vertical delta is in practice the only
809
    /// input such a box can ever receive.
810
    ///
811
    /// Only applies when the delta is purely vertical and the target has no
812
    /// vertical travel whatsoever: a box that scrolls both ways keeps both
813
    /// axes, and a real horizontal delta is passed through untouched.
814
    ///
815
    /// The RAW device delta was already stored in `pending_wheel_event` above,
816
    /// so wheel-as-zoom widgets still see what the hardware actually reported.
817
9
    fn map_wheel_onto_the_only_scrollable_axis(
818
9
        &self,
819
9
        dom_id: DomId,
820
9
        node_id: NodeId,
821
9
        delta_x: f32,
822
9
        delta_y: f32,
823
9
    ) -> (f32, f32) {
824
        const EPS: f32 = 0.5;
825
9
        if delta_x.abs() > EPS || delta_y.abs() <= EPS {
826
1
            return (delta_x, delta_y);
827
8
        }
828
8
        let Some(state) = self.states.get(&(dom_id, node_id)) else {
829
            return (delta_x, delta_y);
830
        };
831
8
        let (max_x, max_y) = state.max_scroll_offsets();
832
8
        if max_y <= EPS && max_x > EPS {
833
1
            (delta_y, 0.0)
834
        } else {
835
7
            (delta_x, delta_y)
836
        }
837
9
    }
838

            
839
    /// MWA-B10: the a11y tree's scroll surface for a node — current offset
840
    /// plus max travel per axis, or `None` when the node isn't scrollable.
841
    /// Screen readers use this (with the ScrollUp/Down/... actions) to
842
    /// drive the same inbound handler mouse users exercise.
843
    #[must_use]
844
310534
    pub fn a11y_scroll_info(
845
310534
        &self,
846
310534
        dom_id: DomId,
847
310534
        node_id: NodeId,
848
310534
    ) -> Option<(LogicalPosition, f32, f32)> {
849
310534
        let state = self.states.get(&(dom_id, node_id))?;
850
832
        let (max_x, max_y) = state.max_scroll_offsets();
851
832
        if max_x <= 0.0 && max_y <= 0.0 {
852
23
            return None;
853
809
        }
854
809
        Some((state.current_offset, max_x, max_y))
855
310534
    }
856

            
857
    /// `true` when the node still has travel in the direction of the
858
    /// normalized delta on at least one moved axis — the boundary-handoff
859
    /// test for [`select_scroll_target`](Self::select_scroll_target).
860
32
    fn can_consume_delta(&self, dom_id: DomId, node_id: NodeId, eff_x: f32, eff_y: f32) -> bool {
861
        const EPS: f32 = 0.5;
862
32
        let Some(state) = self.states.get(&(dom_id, node_id)) else {
863
2
            return false;
864
        };
865
30
        let (max_x, max_y) = state.max_scroll_offsets();
866
30
        let off = state.current_offset;
867

            
868
30
        let x_ok = if eff_x > EPS {
869
1
            off.x < max_x - EPS
870
29
        } else if eff_x < -EPS {
871
            off.x > EPS
872
        } else {
873
29
            false
874
        };
875
30
        let y_ok = if eff_y > EPS {
876
15
            off.y < max_y - EPS
877
15
        } else if eff_y < -EPS {
878
5
            off.y > EPS
879
        } else {
880
10
            false
881
        };
882
30
        x_ok || y_ok
883
32
    }
884

            
885
    /// Get a clone of the scroll input queue (for sharing with timer callbacks).
886
    ///
887
    /// The timer callback stores this in its `RefAny` data and calls `take_all()`
888
    /// each tick to consume pending inputs.
889
    #[cfg(feature = "std")]
890
    #[must_use]
891
36
    pub fn get_input_queue(&self) -> ScrollInputQueue {
892
36
        self.scroll_input_queue.clone()
893
36
    }
894

            
895
    /// Advances scroll animations by one tick, returns repaint info
896
    #[allow(clippy::suboptimal_flops)]
897
    // mul_add not guaranteed faster/available without target +fma; keep explicit a*b+c
898
    // Instant is a ref-counted FFI clock handle; called by every dll backend's event loop by value.
899
    #[allow(clippy::needless_pass_by_value)]
900
41
    pub fn tick(&mut self, now: Instant) -> ScrollTickResult {
901
41
        let mut result = ScrollTickResult::default();
902
82
        for ((dom_id, node_id), state) in &mut self.states {
903
41
            if let Some(anim) = &state.animation {
904
10
                let elapsed = now.duration_since(&anim.start_time);
905
10
                let t = elapsed.div(&anim.duration).min(1.0);
906
10
                let eased_t = apply_easing(t, anim.easing);
907

            
908
10
                state.current_offset = LogicalPosition {
909
10
                    x: anim.start_offset.x + (anim.target_offset.x - anim.start_offset.x) * eased_t,
910
10
                    y: anim.start_offset.y + (anim.target_offset.y - anim.start_offset.y) * eased_t,
911
10
                };
912
10
                result.needs_repaint = true;
913
10
                result.updated_nodes.push((*dom_id, *node_id));
914

            
915
10
                if t >= 1.0 {
916
6
                    state.animation = None;
917
6
                }
918
31
            }
919
        }
920
41
        result
921
41
    }
922

            
923
    /// Returns `true` if any scroll node has an active easing animation.
924
    ///
925
    /// Used by GPU render paths to skip rendering when the UI is completely
926
    /// static (no scroll animations, no layout changes).
927
    #[must_use]
928
1385
    pub fn has_active_animations(&self) -> bool {
929
1385
        self.states.values().any(|s| s.animation.is_some())
930
1385
    }
931

            
932
    /// The closest node registered as a scroll container, walking up from
933
    /// `node_id`.
934
    ///
935
    /// `inclusivity` decides whether `node_id` itself may be the answer, and
936
    /// the two cases are genuinely different questions:
937
    ///
938
    /// * [`Inclusivity::SelfAndAncestors`] — "which scroll box does this node live in?" A caret
939
    ///   sitting on a `TextInput`'s value `<p>` lives in THAT `<p>`: it is both the IFC root and
940
    ///   the horizontal scroll box.
941
    /// * [`Inclusivity::AncestorsOnly`] — "which OTHER container takes over?" Momentum hand-off
942
    ///   must chain outwards, and the on-screen box of a container is moved only by its ancestors'
943
    ///   scrolling, never its own.
944
    ///
945
    /// This used to be hardcoded to ancestors-only via a `nid != node_id`
946
    /// guard inside the loop, which was a live bug for the first question —
947
    /// see the note on `auto_scroll_timer_callback`.
948
    #[must_use]
949
13
    pub fn find_scroll_parent(
950
13
        &self,
951
13
        dom_id: DomId,
952
13
        node_id: NodeId,
953
13
        node_hierarchy: &[azul_core::styled_dom::NodeHierarchyItem],
954
13
        inclusivity: Inclusivity,
955
13
    ) -> Option<NodeId> {
956
13
        azul_core::styled_dom::hierarchy_ancestors(node_hierarchy, node_id, inclusivity)
957
14
            .find(|nid| self.states.contains_key(&(dom_id, *nid)))
958
13
    }
959

            
960
    /// Check if a node is scrollable (has overflow:scroll/auto and overflowing content)
961
    ///
962
    /// Uses `virtual_scroll_size` (when set) instead of `content_rect` for the
963
    /// overflow check, so `VirtualView` nodes with large virtual content are correctly
964
    /// identified as scrollable even when only a small subset is rendered.
965
30
    fn is_node_scrollable(&self, dom_id: DomId, node_id: NodeId) -> bool {
966
30
        let result = self.states.get(&(dom_id, node_id)).is_some_and(|state| {
967
25
            let effective = state.effective_content_size();
968
25
            let has_horizontal = effective.width > state.container_rect.size.width;
969
25
            let has_vertical = effective.height > state.container_rect.size.height;
970
25
            has_horizontal || has_vertical
971
25
        });
972
30
        result
973
30
    }
974

            
975
    // +spec:overflow:4000a6 - scroll position as offset from scroll origin within scrollport
976
    /// Sets scroll position immediately (no animation), clamped to valid bounds.
977
404
    pub fn set_scroll_position(
978
404
        &mut self,
979
404
        dom_id: DomId,
980
404
        node_id: NodeId,
981
404
        position: LogicalPosition,
982
404
        now: Instant,
983
404
    ) {
984
404
        let state = self
985
404
            .states
986
404
            .entry((dom_id, node_id))
987
404
            .or_insert_with(|| AnimatedScrollState::new(now.clone()));
988
404
        let clamped = state.clamp(position);
989
404
        if (clamped.x - state.current_offset.x).abs() > SCROLL_CHANGE_EPSILON
990
362
            || (clamped.y - state.current_offset.y).abs() > SCROLL_CHANGE_EPSILON
991
297
        {
992
297
            self.scroll_dirty = true;
993
297
        }
994
404
        state.current_offset = clamped;
995
404
        state.animation = None;
996
404
        state.last_activity = now;
997
404
    }
998

            
999
    /// Sets scroll position immediately without clamping.
    ///
    /// Used by the scroll physics timer which does its own rubber-band clamping.
    /// Allows the offset to go outside [0, `max_scroll`] for overscroll/rubber-banding.
15039
    pub fn set_scroll_position_unclamped(
15039
        &mut self,
15039
        dom_id: DomId,
15039
        node_id: NodeId,
15039
        position: LogicalPosition,
15039
        now: Instant,
15039
    ) {
15039
        let state = self
15039
            .states
15039
            .entry((dom_id, node_id))
15039
            .or_insert_with(|| AnimatedScrollState::new(now.clone()));
15039
        if (position.x - state.current_offset.x).abs() > SCROLL_CHANGE_EPSILON
15031
            || (position.y - state.current_offset.y).abs() > SCROLL_CHANGE_EPSILON
14837
        {
14837
            self.scroll_dirty = true;
14837
        }
15039
        state.current_offset = position;
15039
        state.animation = None;
15039
        state.last_activity = now;
15039
    }
    /// Scrolls by a delta amount with animation
6
    pub fn scroll_by(
6
        &mut self,
6
        dom_id: DomId,
6
        node_id: NodeId,
6
        delta: LogicalPosition,
6
        duration: Duration,
6
        easing: EasingFunction,
6
        now: Instant,
6
    ) {
6
        let current = self.get_current_offset(dom_id, node_id).unwrap_or_default();
6
        let target = LogicalPosition {
6
            x: current.x + delta.x,
6
            y: current.y + delta.y,
6
        };
6
        self.scroll_to(dom_id, node_id, target, duration, easing, now);
6
    }
    /// Scrolls to an absolute position with animation
    ///
    /// If duration is zero, the position is set immediately without animation.
212
    pub fn scroll_to(
212
        &mut self,
212
        dom_id: DomId,
212
        node_id: NodeId,
212
        target: LogicalPosition,
212
        duration: Duration,
212
        easing: EasingFunction,
212
        now: Instant,
212
    ) {
        // For zero duration, set position immediately
212
        let is_zero = match &duration {
197
            Duration::System(s) => s.secs == 0 && s.nanos == 0,
15
            Duration::Tick(t) => t.tick_diff == 0,
        };
212
        if is_zero {
201
            self.set_scroll_position(dom_id, node_id, target, now);
201
            return;
11
        }
11
        let state = self
11
            .states
11
            .entry((dom_id, node_id))
11
            .or_insert_with(|| AnimatedScrollState::new(now.clone()));
11
        let clamped_target = state.clamp(target);
11
        state.animation = Some(ScrollAnimation {
11
            start_time: now.clone(),
11
            duration,
11
            start_offset: state.current_offset,
11
            target_offset: clamped_target,
11
            easing,
11
        });
11
        state.last_activity = now;
212
    }
    /// Updates the container and content bounds for a scrollable node
1174
    pub fn update_node_bounds(
1174
        &mut self,
1174
        dom_id: DomId,
1174
        node_id: NodeId,
1174
        container_rect: LogicalRect,
1174
        content_rect: LogicalRect,
1174
        now: Instant,
1174
    ) {
1174
        let state = self
1174
            .states
1174
            .entry((dom_id, node_id))
1174
            .or_insert_with(|| AnimatedScrollState::new(now));
1174
        state.container_rect = container_rect;
1174
        state.content_rect = content_rect;
1174
        state.current_offset = state.clamp(state.current_offset);
1174
    }
    /// Updates virtual scroll bounds for a `VirtualView` node.
    ///
    /// Called after `VirtualView` callback returns to propagate the virtual content size
    /// to the `ScrollManager`. Clamp logic then uses `virtual_scroll_size` (when set)
    /// instead of `content_rect` for max scroll bounds.
    ///
    /// If no scroll state exists yet for this node (because `register_or_update_scroll_node`
    /// hasn't been called yet), this creates a default state so the virtual size is preserved.
884
    pub fn update_virtual_scroll_bounds(
884
        &mut self,
884
        dom_id: DomId,
884
        node_id: NodeId,
884
        virtual_scroll_size: LogicalSize,
884
        virtual_scroll_offset: Option<LogicalPosition>,
884
    ) {
884
        let key = (dom_id, node_id);
884
        let state = self.states.entry(key).or_insert_with(|| {
            // AzInstant (System on std, safe Tick on no-clock targets) — not the
            // WASM-panicking std::time::Instant::now(). (A refinement would thread
            // the window's get_system_time_fn callback through for hookability.)
2
            AnimatedScrollState::new(Instant::now())
2
        });
884
        state.virtual_scroll_size = Some(virtual_scroll_size);
884
        state.virtual_scroll_offset = virtual_scroll_offset;
        // Re-clamp with new virtual bounds
884
        state.current_offset = state.clamp(state.current_offset);
884
    }
    /// Returns the current scroll offset for a node
    #[must_use]
1902684
    pub fn get_current_offset(&self, dom_id: DomId, node_id: NodeId) -> Option<LogicalPosition> {
1902684
        self.states
1902684
            .get(&(dom_id, node_id))
1902684
            .map(|s| s.current_offset)
1902684
    }
    /// Returns the timestamp of last scroll activity for a node
    #[must_use]
16457
    pub fn get_last_activity_time(&self, dom_id: DomId, node_id: NodeId) -> Option<Instant> {
16457
        self.states
16457
            .get(&(dom_id, node_id))
16457
            .map(|s| s.last_activity.clone())
16457
    }
    /// Returns the internal scroll state for a node
    #[must_use]
360753
    pub fn get_scroll_state(&self, dom_id: DomId, node_id: NodeId) -> Option<&AnimatedScrollState> {
360753
        self.states.get(&(dom_id, node_id))
360753
    }
    /// Returns a read-only snapshot of a scroll node's state.
    ///
    /// This is the preferred way for timer callbacks to query scroll state,
    /// since they only have `&CallbackInfo` (read-only access).
    ///
    /// When `virtual_scroll_size` is set (for `VirtualView` nodes), the max scroll
    /// bounds are computed from the virtual size instead of `content_rect`.
    #[must_use]
1090
    pub fn get_scroll_node_info(&self, dom_id: DomId, node_id: NodeId) -> Option<ScrollNodeInfo> {
1090
        let state = self.states.get(&(dom_id, node_id))?;
879
        let (max_x, max_y) = state.max_scroll_offsets();
879
        Some(ScrollNodeInfo {
879
            current_offset: state.current_offset,
879
            container_rect: state.container_rect,
879
            content_rect: state.content_rect,
879
            max_scroll_x: max_x,
879
            max_scroll_y: max_y,
879
            overscroll_behavior_x: state.overscroll_behavior_x,
879
            overscroll_behavior_y: state.overscroll_behavior_y,
879
            overflow_scrolling: state.overflow_scrolling,
879
        })
1090
    }
    /// Whether ANY node in any dom currently has a non-zero scroll offset -
    /// the cheap guard for consumers whose rects are content-space and only
    /// valid at zero scroll (patch damage replay, mover blits).
    #[must_use]
16774
    pub fn any_nonzero_offset(&self) -> bool {
16774
        if self.states.is_empty() {
320
            return false;
16454
        }
16454
        self.states
16454
            .values()
16454
            .any(|s| s.current_offset.x != 0.0 || s.current_offset.y != 0.0)
16774
    }
    /// Returns all scroll positions for nodes in a specific DOM
    ///
    /// # `ScrollPosition` coordinate convention (MIXED — read before consuming)
    ///
    /// The two rects of the emitted [`ScrollPosition`] do NOT live in the same
    /// space, and a consumer that subtracts one origin from the other gets
    /// garbage:
    ///
    /// - `parent_rect` — the container's border box in **absolute window coordinates**
    ///   (`calculated_positions[node]`, see `shell2::common::layout::register_scroll_nodes`). Only
    ///   `size` is meaningful to most consumers; the origin exists for `scroll_into_view`.
    /// - `children_rect.origin` — the **scroll offset itself**, i.e. `current_offset`: the distance
    ///   already scrolled, measured from the scroll origin, clamped to `[0, content − container]`.
    ///   It is NOT the absolute position of the scrolled content, and it is NOT relative to
    ///   `parent_rect.origin`. Content is painted at `position − offset` (`cpurender::raster`), so
    ///   a positive value means "scrolled down/right".
    /// - `children_rect.size` — the scrollable content size (the `VirtualView` virtual size when
    ///   one was reported, else the laid-out content size).
    ///
    /// `content_rect.origin` is never carried out of here because it is always
    /// zero in the state (`register_or_update_scroll_node` builds it that way,
    /// and `clamp` reads only its size) — the absolute-content-rect reading of
    /// `children_rect` is not even representable.
    ///
    /// The round trip is the identity: `LayoutWindow::set_scroll_position`
    /// feeds `children_rect.origin` straight back into `set_scroll_position`.
    #[must_use]
31580
    pub fn get_scroll_states_for_dom(&self, dom_id: DomId) -> BTreeMap<NodeId, ScrollPosition> {
        // M12.7: iterating an EMPTY hashbrown map (RawIterRange) mis-lifts to
        // wasm and loops forever (same class as the font-id / GPU-cache loops).
        // For the headless web path `states` is empty; guard it (len-based, no
        // iteration). Desktop unchanged.
31580
        if self.states.is_empty() {
25504
            return BTreeMap::new();
6076
        }
6076
        self.states
6076
            .iter()
6079
            .filter(|((d, _), _)| *d == dom_id)
6076
            .map(|((_, node_id), state)| {
                // Use virtual_scroll_size (from VirtualView callback) when available,
                // otherwise fall back to content_rect.size from layout.
3658
                let effective_content_size = state.effective_content_size();
3658
                (
3658
                    *node_id,
3658
                    ScrollPosition {
3658
                        parent_rect: state.container_rect,
3658
                        children_rect: LogicalRect::new(
3658
                            state.current_offset,
3658
                            effective_content_size,
3658
                        ),
3658
                    },
3658
                )
3658
            })
6076
            .collect()
31580
    }
    /// Registers or updates a scrollable node with its container and content sizes.
    /// This should be called after layout for each node that has overflow:scroll or overflow:auto
    /// with overflowing content.
    ///
    /// If the node already exists, updates container/content rects without changing scroll offset.
    /// If the node is new, initializes with zero scroll offset.
    /// Apply the node's resolved `overscroll-behavior-x` / `-y`.
    ///
    /// Called by `register_scroll_nodes` right before registration, so the
    /// value is in place for the very first physics tick that can see this
    /// node. Kept separate from `register_or_update_scroll_node` on purpose:
    /// that function is also called from tests and other hosts that have no
    /// `StyledDom` to resolve CSS against, and threading two more parameters
    /// through every one of them to pass `Auto` would be noise.
    ///
    /// A node with no state yet is ignored — registration happens immediately
    /// after and seeds `Auto`, which this then overwrites on the next pass.
938
    pub fn set_overscroll_behavior(
938
        &mut self,
938
        dom_id: DomId,
938
        node_id: NodeId,
938
        x: azul_css::props::style::scrollbar::OverscrollBehavior,
938
        y: azul_css::props::style::scrollbar::OverscrollBehavior,
938
    ) {
938
        if let Some(state) = self.states.get_mut(&(dom_id, node_id)) {
445
            state.overscroll_behavior_x = x;
445
            state.overscroll_behavior_y = y;
525
        }
938
    }
1106
    pub fn register_or_update_scroll_node(
1106
        &mut self,
1106
        dom_id: DomId,
1106
        node_id: NodeId,
1106
        container_rect: LogicalRect,
1106
        content_size: LogicalSize,
1106
        now: Instant,
1106
        scrollbar_thickness: f32,
1106
        visual_width_px: f32,
1106
        has_horizontal_scrollbar: bool,
1106
        has_vertical_scrollbar: bool,
1106
    ) {
1106
        let key = (dom_id, node_id);
1106
        let content_rect = LogicalRect {
1106
            origin: LogicalPosition::zero(),
1106
            size: content_size,
1106
        };
1106
        if let Some(existing) = self.states.get_mut(&key) {
            // Was the current offset an OUT-of-bounds overscroll under the OLD
            // bounds? Capture that BEFORE the rects are overwritten. An
            // out-of-bounds value here is a LIVE rubber-band the physics timer
            // owns: snapping it back on a DOM regen makes the next physics tick
            // compute a discontinuous delta that tears the content and drags the
            // overlay scrollbar (the "only on DOM re-generation" artifact) — so
            // preserve it. But an offset that was IN bounds and only exceeds the
            // new max because the CONTENT SHRANK MUST re-clamp, or a shrunk
            // scroller keeps a bogus offset until the next set_scroll_position.
            // (The earlier `if clamped == current_offset { current = clamped }`
            // guard was a no-op that re-clamped NOTHING, so a shrink was never
            // honored.)
            // A real rubber-band is a FINITE out-of-bounds value. Non-finite
            // garbage (a NaN/inf written through set_scroll_position_unclamped)
            // is NOT an overscroll to protect — it must be re-clamped to a sane
            // finite value (clamp maps NaN/inf → 0 / max_travel).
450
            let off = existing.current_offset;
450
            let was_overscrolling =
450
                off.x.is_finite() && off.y.is_finite() && existing.clamp(off) != off;
            // Update rects, keep scroll offset
450
            existing.container_rect = container_rect;
450
            existing.content_rect = content_rect;
450
            existing.scrollbar_thickness = scrollbar_thickness;
450
            existing.visual_width_px = visual_width_px;
450
            existing.has_horizontal_scrollbar = has_horizontal_scrollbar;
450
            existing.has_vertical_scrollbar = has_vertical_scrollbar;
450
            if !was_overscrolling {
450
                existing.current_offset = existing.clamp(existing.current_offset);
450
            }
656
        } else {
656
            // +spec:overflow:8c7aa1 - initial scroll position is zero (scroll origin for LTR/TTB)
656
            self.states.insert(
656
                key,
656
                AnimatedScrollState {
656
                    current_offset: LogicalPosition::zero(),
656
                    animation: None,
656
                    last_activity: now,
656
                    container_rect,
656
                    content_rect,
656
                    virtual_scroll_size: None,
656
                    virtual_scroll_offset: None,
656
                    overscroll_behavior_x:
656
                        azul_css::props::style::scrollbar::OverscrollBehavior::Auto,
656
                    overscroll_behavior_y:
656
                        azul_css::props::style::scrollbar::OverscrollBehavior::Auto,
656
                    overflow_scrolling: azul_css::props::style::scrollbar::OverflowScrolling::Auto,
656
                    scrollbar_thickness,
656
                    visual_width_px,
656
                    has_horizontal_scrollbar,
656
                    has_vertical_scrollbar,
656
                },
656
            );
656
        }
1106
    }
    // Scrollbar State Management
    /// Calculate scrollbar states for all visible scrollbars.
    /// This should be called once per frame after layout is complete.
    /// Uses the shared `compute_scrollbar_geometry()` for consistent geometry.
21034
    pub fn calculate_scrollbar_states(&mut self) {
21034
        self.scrollbar_states.clear();
        // Uses virtual_scroll_size (when set) for the overflow check and thumb ratio,
        // so VirtualView nodes with large virtual content show correct scrollbar geometry.
42068
        for orientation in [
21034
            ScrollbarOrientation::Vertical,
21034
            ScrollbarOrientation::Horizontal,
        ] {
42068
            let states: Vec<_> = self
42068
                .states
42068
                .iter()
42068
                .filter(|(_, s)| {
29200
                    let (effective, container) = match orientation {
14600
                        ScrollbarOrientation::Vertical => (
14600
                            s.effective_content_size().height,
14600
                            s.container_rect.size.height,
14600
                        ),
14600
                        ScrollbarOrientation::Horizontal => (
14600
                            s.effective_content_size().width,
14600
                            s.container_rect.size.width,
14600
                        ),
                    };
29200
                    effective > container
29200
                })
42068
                .map(|((dom_id, node_id), scroll_state)| {
14238
                    let state =
14238
                        Self::calculate_scrollbar_state_from_geometry(scroll_state, orientation);
14238
                    ((*dom_id, *node_id, orientation), state)
14238
                })
42068
                .collect();
42068
            self.scrollbar_states.extend(states);
        }
21034
    }
    /// Calculate scrollbar state using the shared `compute_scrollbar_geometry()`.
14239
    fn calculate_scrollbar_state_from_geometry(
14239
        scroll_state: &AnimatedScrollState,
14239
        orientation: ScrollbarOrientation,
14239
    ) -> ScrollbarState {
14239
        let scrollbar_thickness = if scroll_state.visual_width_px > 0.0 {
13887
            scroll_state.visual_width_px
352
        } else if scroll_state.scrollbar_thickness > 0.0 {
220
            scroll_state.scrollbar_thickness
        } else {
132
            crate::solver3::fc::DEFAULT_SCROLLBAR_WIDTH_PX
        };
14239
        let content_size = scroll_state.effective_content_size();
14239
        let scroll_offset = match orientation {
13914
            ScrollbarOrientation::Vertical => scroll_state.current_offset.y,
325
            ScrollbarOrientation::Horizontal => scroll_state.current_offset.x,
        };
14239
        let has_other_scrollbar = match orientation {
13914
            ScrollbarOrientation::Vertical => scroll_state.has_horizontal_scrollbar,
325
            ScrollbarOrientation::Horizontal => scroll_state.has_vertical_scrollbar,
        };
        // Overlay scrollbars (thickness == 0 from layout) have no arrow buttons
14239
        let is_overlay = scroll_state.scrollbar_thickness == 0.0;
14239
        let button_size = if is_overlay { 0.0 } else { scrollbar_thickness };
14239
        let geom = compute_scrollbar_geometry_with_button_size(
14239
            orientation,
14239
            scroll_state.container_rect,
14239
            content_size,
14239
            scroll_offset,
14239
            scrollbar_thickness,
14239
            has_other_scrollbar,
14239
            button_size,
        );
        // Build ScrollbarState from the shared geometry
14239
        let scale = match orientation {
            ScrollbarOrientation::Vertical => {
13914
                LogicalPosition::new(1.0, geom.track_rect.size.height / scrollbar_thickness)
            }
            ScrollbarOrientation::Horizontal => {
325
                LogicalPosition::new(geom.track_rect.size.width / scrollbar_thickness, 1.0)
            }
        };
14239
        ScrollbarState {
14239
            visible: true,
14239
            orientation,
14239
            base_size: scrollbar_thickness,
14239
            scale,
14239
            thumb_position_ratio: geom.scroll_ratio,
14239
            thumb_size_ratio: geom.thumb_size_ratio,
14239
            track_rect: geom.track_rect,
14239
            button_size: geom.button_size,
14239
            usable_track_length: geom.usable_track_length,
14239
            thumb_length: geom.thumb_length,
14239
            thumb_offset: geom.thumb_offset,
14239
        }
14239
    }
    /// Get scrollbar state for hit-testing
    #[must_use]
4
    pub fn get_scrollbar_state(
4
        &self,
4
        dom_id: DomId,
4
        node_id: NodeId,
4
        orientation: ScrollbarOrientation,
4
    ) -> Option<&ScrollbarState> {
4
        self.scrollbar_states.get(&(dom_id, node_id, orientation))
4
    }
    /// Iterate over all visible scrollbar states
3
    pub(crate) fn iter_scrollbar_states(
3
        &self,
3
    ) -> impl Iterator<Item = ((DomId, NodeId, ScrollbarOrientation), &ScrollbarState)> + '_ {
3
        self.scrollbar_states.iter().map(|(k, v)| (*k, v))
3
    }
    // Scrollbar Hit-Testing
    /// Hit-test scrollbars for a specific node at the given position.
    /// Returns Some if the position is inside a scrollbar for this node.
11
    pub(crate) fn hit_test_scrollbar(
11
        &self,
11
        dom_id: DomId,
11
        node_id: NodeId,
11
        global_pos: LogicalPosition,
11
    ) -> Option<ScrollbarHit> {
        // Check both vertical and horizontal scrollbars for this node
21
        for orientation in [
11
            ScrollbarOrientation::Vertical,
11
            ScrollbarOrientation::Horizontal,
        ] {
21
            let Some(scrollbar_state) = self.scrollbar_states.get(&(dom_id, node_id, orientation))
            else {
12
                continue;
            };
9
            if !scrollbar_state.visible {
1
                continue;
8
            }
            // Check if position is inside scrollbar track using LogicalRect::contains
8
            if !scrollbar_state.track_rect.contains(global_pos) {
7
                continue;
1
            }
            // Calculate local position relative to track origin
1
            let local_pos = LogicalPosition::new(
1
                global_pos.x - scrollbar_state.track_rect.origin.x,
1
                global_pos.y - scrollbar_state.track_rect.origin.y,
            );
            // Determine which component was hit
1
            let component = scrollbar_state.hit_test_component(local_pos);
1
            return Some(ScrollbarHit {
1
                dom_id,
1
                node_id,
1
                orientation,
1
                component,
1
                local_position: local_pos,
1
                global_position: global_pos,
1
            });
        }
10
        None
11
    }
    /// Perform hit-testing for all scrollbars at the given global position.
    ///
    /// This iterates through all visible scrollbars in reverse z-order (top to bottom)
    /// and returns the first hit. Use this when you don't know which node to check.
    ///
    /// For better performance, use `hit_test_scrollbar()` when you already have
    /// a hit-tested node from `WebRender`.
    #[must_use]
13
    pub fn hit_test_scrollbars(&self, global_pos: LogicalPosition) -> Option<ScrollbarHit> {
        // Iterate in reverse order to hit top-most scrollbars first
13
        for ((dom_id, node_id, orientation), scrollbar_state) in self.scrollbar_states.iter().rev()
        {
10
            if !scrollbar_state.visible {
1
                continue;
9
            }
            // Check if position is inside scrollbar track
9
            if !scrollbar_state.track_rect.contains(global_pos) {
8
                continue;
1
            }
            // Calculate local position relative to track origin
1
            let local_pos = LogicalPosition::new(
1
                global_pos.x - scrollbar_state.track_rect.origin.x,
1
                global_pos.y - scrollbar_state.track_rect.origin.y,
            );
            // Determine which component was hit
1
            let component = scrollbar_state.hit_test_component(local_pos);
1
            return Some(ScrollbarHit {
1
                dom_id: *dom_id,
1
                node_id: *node_id,
1
                orientation: *orientation,
1
                component,
1
                local_position: local_pos,
1
                global_position: global_pos,
1
            });
        }
12
        None
13
    }
}
// AnimatedScrollState Implementation
impl AnimatedScrollState {
    /// The size scroll bounds are computed against: the VirtualView-published
    /// virtual size when this node hosts one, else the laid-out content size.
    /// THE single owner of that rule — every consumer (clamping, wheel
    /// redirection, scrollability, thumb geometry, the per-dom snapshot) goes
    /// through this instead of re-deriving the `map_or` by hand.
    #[must_use]
52259
    pub fn effective_content_size(&self) -> LogicalSize {
52259
        self.virtual_scroll_size.unwrap_or(self.content_rect.size)
52259
    }
    /// Max positive scroll offset per axis, from `effective_content_size`
    /// against the container. Zero on non-overflowing axes.
    #[must_use]
5137
    pub fn max_scroll_offsets(&self) -> (f32, f32) {
5137
        let effective = self.effective_content_size();
5137
        (
5137
            (effective.width - self.container_rect.size.width).max(0.0),
5137
            (effective.height - self.container_rect.size.height).max(0.0),
5137
        )
5137
    }
    // +spec:overflow:60f6a1 - scroll origin defaults to block-start inline-start corner (0,0)
    /// Create a new scroll state initialized at offset (0, 0).
1833
    pub(crate) const fn new(now: Instant) -> Self {
1833
        Self {
1833
            current_offset: LogicalPosition::zero(),
1833
            animation: None,
1833
            last_activity: now,
1833
            container_rect: LogicalRect::zero(),
1833
            content_rect: LogicalRect::zero(),
1833
            virtual_scroll_size: None,
1833
            virtual_scroll_offset: None,
1833
            overscroll_behavior_x: azul_css::props::style::scrollbar::OverscrollBehavior::Auto,
1833
            overscroll_behavior_y: azul_css::props::style::scrollbar::OverscrollBehavior::Auto,
1833
            overflow_scrolling: azul_css::props::style::scrollbar::OverflowScrolling::Auto,
1833
            scrollbar_thickness: crate::solver3::fc::DEFAULT_SCROLLBAR_WIDTH_PX,
1833
            visual_width_px: 0.0,
1833
            has_horizontal_scrollbar: false,
1833
            has_vertical_scrollbar: false,
1833
        }
1833
    }
    /// Clamp a scroll position to valid bounds (0 to `max_scroll`).
    ///
    /// When `virtual_scroll_size` is set (for `VirtualView` nodes), the max bounds
    /// are computed from the virtual size instead of `content_rect`.
3388
    pub(crate) fn clamp(&self, position: LogicalPosition) -> LogicalPosition {
3388
        let (max_x, max_y) = self.max_scroll_offsets();
3388
        LogicalPosition {
3388
            x: position.x.max(0.0).min(max_x),
3388
            y: position.y.max(0.0).min(max_y),
3388
        }
3388
    }
}
// Easing Functions
/// Apply an easing function to a normalized time value (0.0 to 1.0).
/// Used by `ScrollAnimation::tick()` for smooth scroll animations.
#[allow(clippy::suboptimal_flops)] // mul_add not guaranteed faster/available without target +fma;
                                   // keep explicit a*b+c
445
pub(crate) fn apply_easing(t: f32, easing: EasingFunction) -> f32 {
445
    match easing {
119
        EasingFunction::Linear => t,
111
        EasingFunction::EaseOut => 1.0 - (1.0 - t).powi(3),
        EasingFunction::EaseInOut => {
112
            if t < 0.5 {
56
                4.0 * t * t * t
            } else {
56
                1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
            }
        }
        // Critically-damped spring released at the target (x(t) settles as
        // (1+ωt)·e^(−ωt)): position = 1 − (1+ωt)e^(−ωt), ω chosen so the
        // curve is within ~0.6% of the target at t = 1 (ω = 7). The exact
        // landing is guaranteed by the clamp below — no asymptotic crawl.
        // Same curve family the scroll physics integrates numerically
        // (spring_constant_from_bounce_duration), evaluated analytically.
        EasingFunction::Spring => {
            const OMEGA: f32 = 7.0;
103
            let settle = 1.0 - (1.0 + OMEGA * t) * (-OMEGA * t).exp();
            // Normalize so t = 1 maps EXACTLY to 1.0: `end` goes through
            // the SAME arithmetic as settle(1), so the division is 1.0 in
            // f32 bit-for-bit (a hand-typed constant differed in the last
            // ulp and t=1 landed at 0.99999994).
103
            let end = 1.0 - (1.0 + OMEGA) * (-OMEGA).exp();
103
            (settle / end).clamp(0.0, 1.0)
        }
    }
445
}
#[cfg(test)]
mod spring_easing_laws {
    use azul_core::events::EasingFunction;
    use super::*;
    #[test]
1
    fn spring_hits_both_endpoints_exactly_and_is_monotone() {
1
        assert_eq!(apply_easing(0.0, EasingFunction::Spring), 0.0);
1
        assert_eq!(apply_easing(1.0, EasingFunction::Spring), 1.0);
1
        let mut prev = 0.0f32;
101
        for i in 1..=100 {
100
            let v = apply_easing(i as f32 / 100.0, EasingFunction::Spring);
100
            assert!(v >= prev, "monotone: {prev} -> {v} at step {i}");
100
            assert!((0.0..=1.0).contains(&v));
100
            prev = v;
        }
1
    }
    #[test]
1
    fn spring_front_loads_motion_like_a_released_spring() {
        // More than 60% of the distance covered by half time (fast pull,
        // gentle landing) — distinguishes it from Linear and EaseInOut.
1
        let half = apply_easing(0.5, EasingFunction::Spring);
1
        assert!(half > 0.6, "front-loaded: {half}");
1
        assert!(half > apply_easing(0.5, EasingFunction::Linear));
1
    }
}
impl crate::managers::NodeIdRemap for ScrollManager {
    /// Rewrite every `(DomId, NodeId)` key for `dom` and DROP the scroll state of
    /// nodes that were unmounted.
    ///
    /// The previous implementation only rewrote keys whose id actually changed and
    /// *kept* everything else "conservatively" — which silently re-attached the
    /// scroll offset of a deleted node to whatever node inherited its index.
    /// `node_moves` contains an entry for every matched node, so "absent from the
    /// map" unambiguously means "unmounted".
448
    fn remap_node_ids(&mut self, dom: DomId, map: &crate::managers::NodeIdMap) {
448
        crate::managers::remap_dom_keys(&mut self.states, dom, map);
448
        let old = core::mem::take(&mut self.scrollbar_states);
770
        for ((d, old_node_id, orientation), state) in old {
322
            if d != dom {
320
                self.scrollbar_states
320
                    .insert((d, old_node_id, orientation), state);
322
            } else if let Some(new_node_id) = map.resolve(old_node_id) {
1
                self.scrollbar_states
1
                    .insert((d, new_node_id, orientation), state);
1
            }
        }
448
    }
}
// ============================================================================
// Natural-scroll direction — unit tests (#17)
// ============================================================================
#[cfg(all(test, feature = "std"))]
mod natural_scroll_tests {
    use azul_core::{
        dom::{DomId, NodeId},
        geom::LogicalPosition,
        task::Instant,
    };
    use super::*;
4
    fn raw_input(dx: f32, dy: f32) -> ScrollInput {
4
        ScrollInput {
4
            dom_id: DomId::ROOT_ID,
4
            node_id: NodeId::new(0),
4
            delta: LogicalPosition::new(dx, dy),
4
            timestamp: Instant::now(),
4
            source: ScrollInputSource::WheelDiscrete,
4
            device: ScrollInputDevice::TestDriver,
4
        }
4
    }
    #[test]
    #[allow(clippy::float_cmp)] // test asserts exact float equality on deterministic values
1
    fn default_is_traditional_and_inverts_raw_delta() {
        // With AZ_NATURAL_SCROLL unset, the default is traditional: the offset
        // delta is the NEGATION of the raw input — exactly what the per-platform
        // `-delta` hardcodes used to do, now centralised.
1
        let mut m = ScrollManager::new();
1
        assert!(!m.is_natural_scroll(), "default must be traditional");
1
        m.record_scroll_input(raw_input(3.0, 10.0));
1
        let q = m.get_input_queue().take_all();
1
        assert_eq!(q.len(), 1);
1
        assert_eq!(q[0].delta.x, -3.0, "x must be inverted by the default sign");
1
        assert_eq!(
1
            q[0].delta.y, -10.0,
            "y must be inverted by the default sign"
        );
1
    }
    #[test]
    #[allow(clippy::float_cmp)] // test asserts exact float equality on deterministic values
1
    fn natural_passes_raw_delta_through() {
1
        let mut m = ScrollManager::new();
1
        m.set_natural_scroll(true);
1
        assert!(m.is_natural_scroll());
1
        m.record_scroll_input(raw_input(3.0, 10.0));
1
        let q = m.get_input_queue().take_all();
1
        assert_eq!(q.len(), 1);
1
        assert_eq!(q[0].delta.x, 3.0, "natural mode must NOT invert x");
1
        assert_eq!(q[0].delta.y, 10.0, "natural mode must NOT invert y");
1
    }
    #[test]
    #[allow(clippy::float_cmp)] // test asserts exact float equality on deterministic values
1
    fn toggling_flips_sign_for_subsequent_input() {
        // Same raw input, opposite directions before/after the toggle — proves the
        // single flag is the only thing controlling direction.
1
        let mut m = ScrollManager::new();
1
        m.record_scroll_input(raw_input(0.0, 5.0));
1
        m.set_natural_scroll(true);
1
        m.record_scroll_input(raw_input(0.0, 5.0));
1
        let q = m.get_input_queue().take_all();
1
        assert_eq!(q.len(), 2);
1
        assert_eq!(q[0].delta.y, -5.0, "traditional first");
1
        assert_eq!(q[1].delta.y, 5.0, "natural after toggle");
1
    }
    // MWA-B2: nested-scroll target selection (innermost-first + handoff).
3
    fn nested_setup() -> (ScrollManager, DomId, NodeId, NodeId) {
        use azul_core::geom::{LogicalRect, LogicalSize};
3
        let now = Instant::now();
3
        let mut m = ScrollManager::new();
3
        let dom = DomId::ROOT_ID;
        // Ancestors have LOWER arena ids than descendants.
3
        let outer = NodeId::from_usize(1).unwrap();
3
        let inner = NodeId::from_usize(9).unwrap();
        // Outer: 200x200 viewport over 200x1000 content → max_y = 800.
3
        m.register_or_update_scroll_node(
3
            dom,
3
            outer,
3
            LogicalRect {
3
                origin: LogicalPosition::zero(),
3
                size: LogicalSize {
3
                    width: 200.0,
3
                    height: 200.0,
3
                },
3
            },
3
            LogicalSize {
3
                width: 200.0,
3
                height: 1000.0,
3
            },
3
            now.clone(),
            8.0,
            8.0,
            false,
            true,
        );
        // Inner: 100x100 viewport over 100x300 content → max_y = 200.
3
        m.register_or_update_scroll_node(
3
            dom,
3
            inner,
3
            LogicalRect {
3
                origin: LogicalPosition::zero(),
3
                size: LogicalSize {
3
                    width: 100.0,
3
                    height: 100.0,
3
                },
3
            },
3
            LogicalSize {
3
                width: 100.0,
3
                height: 300.0,
3
            },
3
            now,
            8.0,
            8.0,
            false,
            true,
        );
3
        (m, dom, outer, inner)
3
    }
    #[test]
1
    fn nested_scroll_prefers_innermost_with_room() {
1
        let (m, dom, outer, inner) = nested_setup();
        // Innermost-first candidate order, scrolling "down" (eff +y).
1
        let picked = m.select_scroll_target([(dom, inner), (dom, outer)].into_iter(), 0.0, 1.0);
1
        assert_eq!(picked, Some((dom, inner)), "inner has room → inner wins");
1
    }
    #[test]
1
    fn nested_scroll_hands_off_to_ancestor_at_boundary() {
1
        let (mut m, dom, outer, inner) = nested_setup();
        // Pin the inner container at its bottom edge (max_y = 200).
1
        m.states.get_mut(&(dom, inner)).unwrap().current_offset =
1
            LogicalPosition { x: 0.0, y: 200.0 };
1
        let down = m.select_scroll_target([(dom, inner), (dom, outer)].into_iter(), 0.0, 1.0);
1
        assert_eq!(down, Some((dom, outer)), "inner pinned at bottom → handoff");
1
        let up = m.select_scroll_target([(dom, inner), (dom, outer)].into_iter(), 0.0, -1.0);
1
        assert_eq!(
            up,
1
            Some((dom, inner)),
            "inner has room upward → inner again"
        );
1
    }
    #[test]
1
    fn nested_scroll_falls_back_to_innermost_when_all_pinned() {
1
        let (mut m, dom, outer, inner) = nested_setup();
1
        m.states.get_mut(&(dom, inner)).unwrap().current_offset =
1
            LogicalPosition { x: 0.0, y: 200.0 };
1
        m.states.get_mut(&(dom, outer)).unwrap().current_offset =
1
            LogicalPosition { x: 0.0, y: 800.0 };
1
        let picked = m.select_scroll_target([(dom, inner), (dom, outer)].into_iter(), 0.0, 1.0);
1
        assert_eq!(
            picked,
1
            Some((dom, inner)),
            "everything pinned → innermost fallback (gesture stays under pointer)"
        );
1
    }
}
// ============================================================================
// Adversarial unit tests (autotest fleet)
//
// Hostile inputs for every category in the task file: numeric (NaN / ±inf /
// MIN / MAX / zero / saturation), predicates (invariants at the boundary),
// getters (defined value on a default/empty instance) and constructors.
// Every assertion below documents the *actual* behavior — nothing is weakened
// to make it pass.
// ============================================================================
#[cfg(all(test, feature = "std"))]
mod autotest_generated {
    #![allow(clippy::float_cmp)] // tests assert exact float results on deterministic inputs
    use std::collections::HashMap;
    use azul_core::{
        dom::{DomId, NodeId, ScrollbarOrientation},
        events::EasingFunction,
        geom::{LogicalPosition, LogicalRect, LogicalSize},
        hit_test::{FullHitTest, HitTest, OverflowingScrollNode, ScrollHitTestItem},
        styled_dom::NodeHierarchyItem,
        task::{Duration, Instant, SystemTick, SystemTickDiff, SystemTimeDiff},
    };
    use super::*;
    use crate::managers::hover::HoverManager;
    // ---------------------------------------------------------------- helpers
    const DOM: DomId = DomId::ROOT_ID;
    const DOM1: DomId = DomId { inner: 1 };
    fn node(i: usize) -> NodeId {
        NodeId::new(i)
    }
    /// Deterministic tick-clock instant — no wall clock, no flakiness.
    fn at(t: u64) -> Instant {
        Instant::Tick(SystemTick::new(t))
    }
    fn tick_dur(d: u64) -> Duration {
        Duration::Tick(SystemTickDiff { tick_diff: d })
    }
    fn sys_dur(secs: u64, nanos: u32) -> Duration {
        Duration::System(SystemTimeDiff { secs, nanos })
    }
    fn pos(x: f32, y: f32) -> LogicalPosition {
        LogicalPosition::new(x, y)
    }
    fn size(w: f32, h: f32) -> LogicalSize {
        LogicalSize::new(w, h)
    }
    fn rect(x: f32, y: f32, w: f32, h: f32) -> LogicalRect {
        LogicalRect::new(pos(x, y), size(w, h))
    }
    /// A manager with node 0 registered: `container` viewport over `content`.
    fn mgr(container: LogicalSize, content: LogicalSize) -> ScrollManager {
        let mut m = ScrollManager::new();
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            LogicalRect::new(LogicalPosition::zero(), container),
            content,
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        m
    }
    /// A bare `AnimatedScrollState` with the given container/content geometry.
    fn state(container: LogicalSize, content: LogicalSize) -> AnimatedScrollState {
        let mut s = AnimatedScrollState::new(at(0));
        s.container_rect = LogicalRect::new(LogicalPosition::zero(), container);
        s.content_rect = LogicalRect::new(LogicalPosition::zero(), content);
        s
    }
    fn input(dx: f32, dy: f32, ts: u64) -> ScrollInput {
        ScrollInput {
            dom_id: DOM,
            node_id: node(0),
            delta: pos(dx, dy),
            timestamp: at(ts),
            source: ScrollInputSource::WheelDiscrete,
            device: ScrollInputDevice::TestDriver,
        }
    }
    fn scrollbar(
        orientation: ScrollbarOrientation,
        track: LogicalRect,
        button_size: f32,
        thumb_offset: f32,
        thumb_length: f32,
    ) -> ScrollbarState {
        ScrollbarState {
            visible: true,
            orientation,
            base_size: 16.0,
            scale: LogicalPosition::new(1.0, 1.0),
            thumb_position_ratio: 0.0,
            thumb_size_ratio: 0.5,
            track_rect: track,
            button_size,
            usable_track_length: 0.0,
            thumb_length,
            thumb_offset,
        }
    }
    /// A `HoverManager` whose current mouse hit-test reports `nodes` as scroll
    /// hit-test nodes in `DOM` (BTreeMap key order; `record_scroll_from_hit_test`
    /// walks them in reverse = innermost-first).
    fn hover_over(nodes: &[usize]) -> HoverManager {
        let mut ht = HitTest::empty();
        for n in nodes {
            ht.scroll_hit_test_nodes.insert(
                node(*n),
                ScrollHitTestItem {
                    point_in_viewport: LogicalPosition::zero(),
                    point_relative_to_item: Default::default(),
                    scroll_node: OverflowingScrollNode::default(),
                },
            );
        }
        let mut full = FullHitTest::empty(None);
        full.hovered_nodes.insert(DOM, ht);
        let mut hm = HoverManager::new();
        hm.push_hit_test(InputPointId::Mouse, full);
        hm
    }
    // ============================================================ apply_easing
    // (numeric: zero / min_max / negative / overflow / nan_inf)
    #[test]
    fn apply_easing_endpoints_are_exact_for_every_curve() {
        // The one invariant every easing curve must satisfy: f(0) == 0, f(1) == 1.
        // A violation here would make animations jump at their first/last tick.
        for e in [
            EasingFunction::Linear,
            EasingFunction::EaseOut,
            EasingFunction::EaseInOut,
        ] {
            assert_eq!(apply_easing(0.0, e), 0.0, "f(0) must be 0 for {e:?}");
            assert_eq!(apply_easing(1.0, e), 1.0, "f(1) must be 1 for {e:?}");
        }
    }
    #[test]
    fn apply_easing_is_monotonic_and_bounded_on_the_unit_interval() {
        for e in [
            EasingFunction::Linear,
            EasingFunction::EaseOut,
            EasingFunction::EaseInOut,
        ] {
            let mut prev = f32::NEG_INFINITY;
            for i in 0..=100 {
                let t = i as f32 / 100.0;
                let v = apply_easing(t, e);
                assert!(v.is_finite(), "{e:?}({t}) must be finite, got {v}");
                assert!(
                    (-1e-6..=1.0 + 1e-6).contains(&v),
                    "{e:?}({t}) = {v} escaped [0, 1]"
                );
                assert!(v >= prev - 1e-6, "{e:?} must not go backwards at t={t}");
                prev = v;
            }
        }
    }
    #[test]
    fn apply_easing_nan_propagates_without_panicking() {
        // NaN in => NaN out for every curve (no comparison panic, no unwrap).
        for e in [
            EasingFunction::Linear,
            EasingFunction::EaseOut,
            EasingFunction::EaseInOut,
        ] {
            assert!(
                apply_easing(f32::NAN, e).is_nan(),
                "{e:?}(NaN) must be NaN, not a silently-wrong number"
            );
        }
    }
    #[test]
    fn apply_easing_infinities_saturate_to_infinity_not_panic() {
        assert_eq!(
            apply_easing(f32::INFINITY, EasingFunction::Linear),
            f32::INFINITY
        );
        assert_eq!(
            apply_easing(f32::NEG_INFINITY, EasingFunction::Linear),
            f32::NEG_INFINITY
        );
        // EaseOut: 1 - (1 - inf)^3 = 1 + inf
        assert_eq!(
            apply_easing(f32::INFINITY, EasingFunction::EaseOut),
            f32::INFINITY
        );
        assert_eq!(
            apply_easing(f32::NEG_INFINITY, EasingFunction::EaseOut),
            f32::NEG_INFINITY
        );
        // EaseInOut: t >= 0.5 branch for +inf, t < 0.5 branch for -inf
        assert_eq!(
            apply_easing(f32::INFINITY, EasingFunction::EaseInOut),
            f32::INFINITY
        );
        assert_eq!(
            apply_easing(f32::NEG_INFINITY, EasingFunction::EaseInOut),
            f32::NEG_INFINITY
        );
    }
    #[test]
    fn apply_easing_f32_extremes_do_not_panic() {
        // powi(3) overflows f32 for MIN/MAX inputs — must saturate to +-inf,
        // never trap. (Callers clamp t to [0, 1]; this is the defense in depth.)
        for e in [
            EasingFunction::Linear,
            EasingFunction::EaseOut,
            EasingFunction::EaseInOut,
        ] {
            let hi = apply_easing(f32::MAX, e);
            let lo = apply_easing(f32::MIN, e);
            assert!(!hi.is_nan(), "{e:?}(f32::MAX) must not be NaN");
            assert!(!lo.is_nan(), "{e:?}(f32::MIN) must not be NaN");
        }
        // Subnormal / smallest positive: stays ~0, no denormal blowup.
        assert!(apply_easing(f32::MIN_POSITIVE, EasingFunction::EaseInOut).abs() < 1e-30);
    }
    #[test]
    fn apply_easing_negative_t_is_deterministic_extrapolation() {
        // Out-of-range t is not clamped by apply_easing (the caller does that);
        // pin the exact extrapolated values so a silent change is caught.
        assert_eq!(apply_easing(-1.0, EasingFunction::Linear), -1.0);
        assert_eq!(apply_easing(-1.0, EasingFunction::EaseOut), -7.0);
        assert_eq!(apply_easing(-1.0, EasingFunction::EaseInOut), -4.0);
    }
    #[test]
    fn apply_easing_ease_in_out_is_continuous_at_the_branch_boundary() {
        // t == 0.5 takes the `else` branch; both halves must meet at 0.5.
        assert_eq!(apply_easing(0.5, EasingFunction::EaseInOut), 0.5);
        let just_below = apply_easing(0.499_999, EasingFunction::EaseInOut);
        assert!(
            (just_below - 0.5).abs() < 1e-4,
            "discontinuity at the 0.5 branch: {just_below}"
        );
        assert_eq!(apply_easing(0.5, EasingFunction::EaseOut), 0.875);
    }
    // ================================================ AnimatedScrollState::new
    // (constructor: no_panic / invariants_hold)
    #[test]
    fn animated_scroll_state_new_starts_at_scroll_origin() {
        let s = AnimatedScrollState::new(at(0));
        assert_eq!(s.current_offset, LogicalPosition::zero());
        assert!(s.animation.is_none());
        assert_eq!(s.container_rect, LogicalRect::zero());
        assert_eq!(s.content_rect, LogicalRect::zero());
        assert!(s.virtual_scroll_size.is_none());
        assert!(s.virtual_scroll_offset.is_none());
        assert!(!s.has_horizontal_scrollbar);
        assert!(!s.has_vertical_scrollbar);
        // A zero-sized state has no travel: clamp must pin everything to origin.
        assert_eq!(s.clamp(pos(1e9, 1e9)), LogicalPosition::zero());
    }
    // ============================================== AnimatedScrollState::clamp
    // (numeric: zero / min_max / negative / overflow)
    #[test]
    fn clamp_pins_to_zero_and_max_travel() {
        let s = state(size(100.0, 100.0), size(100.0, 500.0));
        // max_x = 0 (no horizontal overflow), max_y = 400.
        assert_eq!(s.clamp(pos(0.0, 0.0)), pos(0.0, 0.0));
        assert_eq!(s.clamp(pos(50.0, 250.0)), pos(0.0, 250.0));
        assert_eq!(s.clamp(pos(-1.0, -1.0)), pos(0.0, 0.0));
        assert_eq!(s.clamp(pos(9999.0, 9999.0)), pos(0.0, 400.0));
    }
    /// A wheel gesture must OPEN and CLOSE, and a second one must open again.
    ///
    /// The bug this pins: `settle_scroll_gesture` had no caller, so a
    /// `WheelDiscrete` gesture never closed. That loses more than `ScrollEnd` —
    /// `note_scroll_phase` only opens a gesture when one is not already open,
    /// so every wheel scroll AFTER the first also fired nothing, for the life
    /// of the window.
    #[test]
    fn a_wheel_gesture_opens_closes_and_can_open_again() {
        let mut s = ScrollManager::default();
        s.note_scroll_phase(ScrollInputSource::WheelDiscrete);
        assert_eq!(
            s.pending_scroll_phase,
            vec![ScrollPhaseTransition::Started],
            "first wheel delta must open a gesture",
        );
        // More deltas in the same gesture do not re-open it.
        s.note_scroll_phase(ScrollInputSource::WheelDiscrete);
        assert_eq!(
            s.pending_scroll_phase,
            vec![ScrollPhaseTransition::Started],
            "a gesture already open must not emit a second Start",
        );
        // The physics timer running dry is the only end a wheel has.
        s.settle_scroll_gesture();
        assert_eq!(
            s.pending_scroll_phase,
            vec![ScrollPhaseTransition::Started, ScrollPhaseTransition::Ended],
            "the timer running dry must close the gesture",
        );
        // The drain clears the queue (event.rs does this each pass).
        s.pending_scroll_phase.clear();
        // THE REGRESSION: without the settle above, this emitted nothing.
        s.note_scroll_phase(ScrollInputSource::WheelDiscrete);
        assert_eq!(
            s.pending_scroll_phase,
            vec![ScrollPhaseTransition::Started],
            "a later wheel gesture must open again after the previous closed",
        );
    }
    /// Settling with no gesture open is a no-op, which is what makes the
    /// unconditional call in the timer's terminate branch safe: that timer also
    /// runs for trackpad flicks (already closed by TrackpadEnd) and for
    /// programmatic scrolls, neither of which should emit anything.
    #[test]
    fn settling_without_a_gesture_emits_nothing() {
        let mut s = ScrollManager::default();
        s.settle_scroll_gesture();
        assert!(s.pending_scroll_phase.is_empty());
        s.note_scroll_phase(ScrollInputSource::Programmatic);
        s.note_scroll_phase(ScrollInputSource::AnimateTo);
        s.settle_scroll_gesture();
        assert!(
            s.pending_scroll_phase.is_empty(),
            "programmatic scrolls are not gestures and must not open one",
        );
    }
    #[test]
    fn clamp_never_produces_negative_max_when_content_is_smaller_than_container() {
        // Content smaller than the viewport => max travel is 0, not negative.
        let s = state(size(500.0, 500.0), size(10.0, 10.0));
        assert_eq!(s.clamp(pos(100.0, 100.0)), LogicalPosition::zero());
        assert_eq!(s.clamp(pos(-100.0, -100.0)), LogicalPosition::zero());
    }
    #[test]
    fn clamp_nan_position_collapses_to_origin_never_stores_nan() {
        // f32::max(NaN, 0.0) == 0.0, so a NaN offset is sanitized to the origin.
        // This is the property the whole scroll pipeline relies on to stay finite.
        let s = state(size(100.0, 100.0), size(100.0, 500.0));
        let c = s.clamp(pos(f32::NAN, f32::NAN));
        assert!(!c.x.is_nan() && !c.y.is_nan(), "clamp must not leak NaN");
        assert_eq!(c, LogicalPosition::zero());
    }
    #[test]
    fn clamp_infinite_position_saturates_to_max_travel() {
        let s = state(size(100.0, 100.0), size(100.0, 500.0));
        assert_eq!(s.clamp(pos(f32::INFINITY, f32::INFINITY)), pos(0.0, 400.0));
        assert_eq!(
            s.clamp(pos(f32::NEG_INFINITY, f32::NEG_INFINITY)),
            LogicalPosition::zero()
        );
        assert_eq!(s.clamp(pos(f32::MAX, f32::MAX)), pos(0.0, 400.0));
        assert_eq!(s.clamp(pos(f32::MIN, f32::MIN)), LogicalPosition::zero());
    }
    #[test]
    fn clamp_nan_geometry_degrades_to_zero_travel() {
        // A NaN content size must not poison the offset: (NaN - w).max(0.0) == 0.0.
        let s = state(size(100.0, 100.0), size(f32::NAN, f32::NAN));
        let c = s.clamp(pos(50.0, 50.0));
        assert!(!c.x.is_nan() && !c.y.is_nan());
        assert_eq!(c, LogicalPosition::zero());
    }
    #[test]
    fn clamp_infinite_content_minus_infinite_container_is_zero_travel_not_nan() {
        // inf - inf = NaN; `.max(0.0)` rescues it to 0.
        let s = state(
            size(f32::INFINITY, f32::INFINITY),
            size(f32::INFINITY, f32::INFINITY),
        );
        let c = s.clamp(pos(10.0, 10.0));
        assert!(!c.x.is_nan() && !c.y.is_nan());
        assert_eq!(c, LogicalPosition::zero());
    }
    #[test]
    fn clamp_prefers_virtual_scroll_size_over_content_rect() {
        let mut s = state(size(100.0, 100.0), size(100.0, 120.0));
        assert_eq!(s.clamp(pos(0.0, 1e9)), pos(0.0, 20.0), "content_rect bound");
        s.virtual_scroll_size = Some(size(100.0, 10_000.0));
        assert_eq!(
            s.clamp(pos(0.0, 1e9)),
            pos(0.0, 9900.0),
            "virtual size must override content_rect"
        );
    }
    // ============================================== ScrollInputQueue (std only)
    // (constructor / getter / predicate / numeric)
    #[test]
    fn input_queue_new_is_empty_and_default_matches() {
        let q = ScrollInputQueue::new();
        assert!(!q.has_pending());
        assert!(q.take_all().is_empty());
        assert!(q.take_recent(10).is_empty());
        assert!(!ScrollInputQueue::default().has_pending());
    }
    #[test]
    fn input_queue_take_all_drains_and_preserves_push_order() {
        let q = ScrollInputQueue::new();
        q.push(input(1.0, 1.0, 1));
        q.push(input(2.0, 2.0, 2));
        assert!(q.has_pending());
        let taken = q.take_all();
        assert_eq!(taken.len(), 2);
        assert_eq!(taken[0].delta.x, 1.0);
        assert_eq!(taken[1].delta.x, 2.0);
        assert!(!q.has_pending(), "take_all must drain the queue");
        assert!(
            q.take_all().is_empty(),
            "second take_all is empty, not stale"
        );
    }
    #[test]
    fn input_queue_take_recent_zero_discards_everything() {
        // max_events = 0: `drain(..len - 0)` removes every event. Documented as
        // "older events beyond max_events are discarded" — with 0 that is all of
        // them, and the queue is left empty (the backlog is dropped, not kept).
        let q = ScrollInputQueue::new();
        q.push(input(1.0, 1.0, 1));
        q.push(input(2.0, 2.0, 2));
        let taken = q.take_recent(0);
        assert!(taken.is_empty(), "take_recent(0) must return nothing");
        assert!(
            !q.has_pending(),
            "take_recent(0) must still drain the queue"
        );
    }
    #[test]
    fn input_queue_take_recent_keeps_the_newest_events_sorted_oldest_first() {
        let q = ScrollInputQueue::new();
        // Pushed out of timestamp order on purpose.
        q.push(input(0.0, 0.0, 5));
        q.push(input(0.0, 0.0, 1));
        q.push(input(0.0, 0.0, 3));
        q.push(input(0.0, 0.0, 9));
        let taken = q.take_recent(2);
        assert_eq!(taken.len(), 2, "backlog must be truncated to max_events");
        assert_eq!(taken[0].timestamp, at(5));
        assert_eq!(taken[1].timestamp, at(9), "newest event must be last");
        assert!(!q.has_pending());
    }
    #[test]
    fn input_queue_take_recent_below_limit_returns_push_order_not_sorted() {
        // NOTE: the doc says "sorted by timestamp (newest last)", but the sort
        // only runs on the overflow path (len > max_events). Below the limit the
        // events come back in PUSH order. Pinning the real behavior here.
        let q = ScrollInputQueue::new();
        q.push(input(0.0, 0.0, 5));
        q.push(input(0.0, 0.0, 1));
        q.push(input(0.0, 0.0, 3));
        let taken = q.take_recent(3);
        assert_eq!(taken.len(), 3);
        let stamps: Vec<_> = taken.iter().map(|e| e.timestamp.clone()).collect();
        assert_eq!(stamps, vec![at(5), at(1), at(3)]);
    }
    #[test]
    fn input_queue_take_recent_usize_max_does_not_overflow() {
        // `events.len() - max_events` would underflow if the length guard were
        // wrong; usize::MAX must simply mean "take everything".
        let q = ScrollInputQueue::new();
        q.push(input(1.0, 0.0, 1));
        q.push(input(2.0, 0.0, 2));
        let taken = q.take_recent(usize::MAX);
        assert_eq!(taken.len(), 2);
        assert!(!q.has_pending());
        // Empty queue + usize::MAX: still no underflow, no panic.
        assert!(q.take_recent(usize::MAX).is_empty());
        assert!(q.take_recent(0).is_empty());
    }
    #[test]
    fn input_queue_clone_shares_one_backing_store() {
        // The timer callback holds a clone; a push through either handle must be
        // visible to the other, otherwise inputs would silently vanish.
        let q = ScrollInputQueue::new();
        let c = q.clone();
        c.push(input(1.0, 2.0, 1));
        assert!(q.has_pending(), "clone must not deep-copy the queue");
        assert_eq!(q.take_all().len(), 1);
        assert!(!c.has_pending(), "draining one handle drains both");
    }
    #[test]
    fn input_queue_accepts_non_finite_deltas_without_panicking() {
        let q = ScrollInputQueue::new();
        q.push(input(f32::NAN, f32::INFINITY, 1));
        q.push(input(f32::MAX, f32::MIN, 2));
        let taken = q.take_recent(usize::MAX);
        assert_eq!(taken.len(), 2);
        assert!(taken[0].delta.x.is_nan());
        assert_eq!(taken[0].delta.y, f32::INFINITY);
    }
    // ======================================= ScrollbarState::hit_test_component
    // (numeric: zero / negative / nan_inf / boundary)
    #[test]
    fn hit_test_component_vertical_maps_each_region() {
        let sb = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 16.0, 100.0),
            16.0, // button_size
            10.0, // thumb_offset (from end of top button)
            30.0, // thumb_length
        );
        assert_eq!(
            sb.hit_test_component(pos(8.0, 0.0)),
            ScrollbarComponent::TopButton
        );
        assert_eq!(
            sb.hit_test_component(pos(8.0, 15.9)),
            ScrollbarComponent::TopButton
        );
        assert_eq!(
            sb.hit_test_component(pos(8.0, 99.0)),
            ScrollbarComponent::BottomButton
        );
        // Thumb spans [16 + 10, 16 + 10 + 30] = [26, 56].
        assert_eq!(
            sb.hit_test_component(pos(8.0, 26.0)),
            ScrollbarComponent::Thumb
        );
        assert_eq!(
            sb.hit_test_component(pos(8.0, 56.0)),
            ScrollbarComponent::Thumb
        );
        assert_eq!(
            sb.hit_test_component(pos(8.0, 20.0)),
            ScrollbarComponent::Track
        );
        assert_eq!(
            sb.hit_test_component(pos(8.0, 60.0)),
            ScrollbarComponent::Track
        );
    }
    #[test]
    fn hit_test_component_boundaries_are_exact() {
        let sb = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 16.0, 100.0),
            16.0,
            0.0,
            30.0,
        );
        // y == button_size is NOT the top button (strict <) — it is the thumb start.
        assert_eq!(
            sb.hit_test_component(pos(0.0, 16.0)),
            ScrollbarComponent::Thumb
        );
        // y == track_height - button_size is NOT the bottom button (strict >).
        assert_eq!(
            sb.hit_test_component(pos(0.0, 84.0)),
            ScrollbarComponent::Track
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, 84.001)),
            ScrollbarComponent::BottomButton
        );
    }
    #[test]
    fn hit_test_component_overlay_zero_button_size_has_no_buttons() {
        // Overlay scrollbars get button_size == 0: y == 0 must NOT be a TopButton
        // (strict `<` means the button region is empty).
        let sb = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 8.0, 100.0),
            0.0,
            0.0,
            50.0,
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, 0.0)),
            ScrollbarComponent::Thumb
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, 50.0)),
            ScrollbarComponent::Thumb
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, 60.0)),
            ScrollbarComponent::Track
        );
        // y == track_height is still not "> track_height - 0" ... it IS equal, so Track.
        assert_eq!(
            sb.hit_test_component(pos(0.0, 100.0)),
            ScrollbarComponent::Track
        );
    }
    #[test]
    fn hit_test_component_nan_position_falls_through_to_track() {
        // Every float comparison against NaN is false, so NaN lands in the
        // final `else` — Track. Deterministic, no panic, no phantom button click.
        let sb = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 16.0, 100.0),
            16.0,
            10.0,
            30.0,
        );
        assert_eq!(
            sb.hit_test_component(pos(f32::NAN, f32::NAN)),
            ScrollbarComponent::Track
        );
        let hb = scrollbar(
            ScrollbarOrientation::Horizontal,
            rect(0.0, 0.0, 100.0, 16.0),
            16.0,
            10.0,
            30.0,
        );
        assert_eq!(
            hb.hit_test_component(pos(f32::NAN, f32::NAN)),
            ScrollbarComponent::Track
        );
    }
    #[test]
    fn hit_test_component_infinite_position_picks_an_end_button() {
        let sb = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 16.0, 100.0),
            16.0,
            10.0,
            30.0,
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, f32::NEG_INFINITY)),
            ScrollbarComponent::TopButton
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, f32::INFINITY)),
            ScrollbarComponent::BottomButton
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, f32::MIN)),
            ScrollbarComponent::TopButton
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, f32::MAX)),
            ScrollbarComponent::BottomButton
        );
    }
    #[test]
    fn hit_test_component_ignores_the_cross_axis() {
        // A vertical scrollbar must not care about x (and vice versa) — otherwise
        // a drag that leaves the bar sideways would change component mid-gesture.
        let v = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 16.0, 100.0),
            16.0,
            10.0,
            30.0,
        );
        for x in [-1e9, -1.0, 0.0, 8.0, 1e9, f32::NAN] {
            assert_eq!(
                v.hit_test_component(pos(x, 30.0)),
                ScrollbarComponent::Thumb
            );
        }
        let h = scrollbar(
            ScrollbarOrientation::Horizontal,
            rect(0.0, 0.0, 100.0, 16.0),
            16.0,
            10.0,
            30.0,
        );
        for y in [-1e9, -1.0, 0.0, 8.0, 1e9, f32::NAN] {
            assert_eq!(
                h.hit_test_component(pos(30.0, y)),
                ScrollbarComponent::Thumb
            );
        }
    }
    #[test]
    fn hit_test_component_degenerate_track_shorter_than_buttons_prefers_top() {
        // button_size > track length: the top/bottom regions overlap. First match
        // wins (TopButton) — no panic, no ambiguity.
        let sb = scrollbar(
            ScrollbarOrientation::Vertical,
            rect(0.0, 0.0, 16.0, 4.0),
            16.0,
            0.0,
            0.0,
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, 0.0)),
            ScrollbarComponent::TopButton
        );
        assert_eq!(
            sb.hit_test_component(pos(0.0, 3.0)),
            ScrollbarComponent::TopButton
        );
    }
    // ========================================================= ScrollManager::new
    // (constructor / getters / predicates on an empty instance)
    #[test]
    fn manager_new_is_empty_and_traditional_by_default() {
        let m = ScrollManager::new();
        assert_eq!(m.debug_counts(), (0, 0));
        assert!(!m.has_active_animations());
        assert!(!m.has_pending_scroll_changes());
        assert!(!m.is_natural_scroll());
        assert_eq!(m.scroll_sign(), -1.0);
        assert!(m.pending_wheel_event.is_none());
        assert!(!m.get_input_queue().has_pending());
        // Getters on an empty manager return None / empty, never panic.
        assert!(m.get_current_offset(DOM, node(0)).is_none());
        assert!(m.get_last_activity_time(DOM, node(0)).is_none());
        assert!(m.get_scroll_state(DOM, node(0)).is_none());
        assert!(m.get_scroll_node_info(DOM, node(0)).is_none());
        assert!(m.a11y_scroll_info(DOM, node(0)).is_none());
        assert!(m.get_scroll_states_for_dom(DOM).is_empty());
        assert!(m
            .get_scrollbar_state(DOM, node(0), ScrollbarOrientation::Vertical)
            .is_none());
        assert!(m.hit_test_scrollbars(pos(0.0, 0.0)).is_none());
        assert_eq!(m.iter_scrollbar_states().count(), 0);
        assert!(!m.is_node_scrollable(DOM, node(0)));
        assert!(!m.can_consume_delta(DOM, node(0), 10.0, 10.0));
    }
    #[test]
    fn scroll_sign_flips_with_the_preference() {
        let mut m = ScrollManager::new();
        assert_eq!(m.scroll_sign(), -1.0);
        m.set_natural_scroll(true);
        assert!(m.is_natural_scroll());
        assert_eq!(m.scroll_sign(), 1.0);
        m.set_natural_scroll(false);
        assert_eq!(m.scroll_sign(), -1.0);
        // Idempotent: setting the same value twice must not toggle.
        m.set_natural_scroll(false);
        assert_eq!(m.scroll_sign(), -1.0);
    }
    // ================================================= dirty-flag bookkeeping
    // (predicate: has_pending_scroll_changes / clear_scroll_dirty)
    #[test]
    fn scroll_dirty_is_set_only_on_a_real_move_and_cleared_on_demand() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        assert!(!m.has_pending_scroll_changes());
        // Sub-epsilon move (< SCROLL_CHANGE_EPSILON = 0.01) must NOT dirty the
        // display list — otherwise every trackpad jitter forces a rebuild.
        m.set_scroll_position(DOM, node(0), pos(0.0, 0.005), at(1));
        assert!(
            !m.has_pending_scroll_changes(),
            "0.005px must not be 'moved'"
        );
        m.set_scroll_position(DOM, node(0), pos(0.0, 50.0), at(2));
        assert!(m.has_pending_scroll_changes());
        m.clear_scroll_dirty();
        assert!(!m.has_pending_scroll_changes());
        // Setting the SAME position again is a no-op move: stays clean.
        m.set_scroll_position(DOM, node(0), pos(0.0, 50.0), at(3));
        assert!(!m.has_pending_scroll_changes());
    }
    #[test]
    fn clear_scroll_dirty_on_a_clean_manager_is_a_noop() {
        let mut m = ScrollManager::new();
        m.clear_scroll_dirty();
        m.clear_scroll_dirty();
        assert!(!m.has_pending_scroll_changes());
    }
    // ======================================= set_scroll_position (+unclamped)
    // (numeric: zero / min_max / negative / overflow / nan)
    #[test]
    fn set_scroll_position_clamps_extremes_into_bounds() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(f32::MAX, f32::MAX), at(1));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
        m.set_scroll_position(DOM, node(0), pos(f32::MIN, f32::MIN), at(2));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 0.0)));
        m.set_scroll_position(DOM, node(0), pos(f32::INFINITY, f32::INFINITY), at(3));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
        m.set_scroll_position(DOM, node(0), pos(f32::NAN, f32::NAN), at(4));
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            !off.x.is_nan() && !off.y.is_nan(),
            "clamped path must kill NaN"
        );
        assert_eq!(off, LogicalPosition::zero());
    }
    #[test]
    fn set_scroll_position_cancels_a_running_animation() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 300.0),
            tick_dur(100),
            EasingFunction::Linear,
            at(0),
        );
        assert!(m.has_active_animations());
        m.set_scroll_position(DOM, node(0), pos(0.0, 10.0), at(1));
        assert!(
            !m.has_active_animations(),
            "an explicit set must win over easing"
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 10.0)));
    }
    #[test]
    fn set_scroll_position_on_an_unknown_node_creates_a_pinned_zero_state() {
        // The entry API inserts a zero-sized state, so the offset can only be 0 —
        // and the map grows by exactly one (no unbounded growth per call).
        let mut m = ScrollManager::new();
        m.set_scroll_position(DOM, node(42), pos(500.0, 500.0), at(1));
        assert_eq!(
            m.get_current_offset(DOM, node(42)),
            Some(LogicalPosition::zero())
        );
        assert_eq!(m.debug_counts(), (1, 0));
        m.set_scroll_position(DOM, node(42), pos(600.0, 600.0), at(2));
        assert_eq!(m.debug_counts(), (1, 0), "repeat set must not grow the map");
    }
    #[test]
    fn set_scroll_position_unclamped_keeps_overscroll_values_verbatim() {
        // The physics timer relies on being able to push the offset OUTSIDE
        // [0, max] for rubber-banding — clamping here would kill the bounce.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position_unclamped(DOM, node(0), pos(-50.0, -80.0), at(1));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(-50.0, -80.0)));
        m.set_scroll_position_unclamped(DOM, node(0), pos(0.0, 9999.0), at(2));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 9999.0)));
        assert!(m.has_pending_scroll_changes());
    }
    #[test]
    fn set_scroll_position_unclamped_stores_non_finite_values_unfiltered() {
        // Documents a real hazard: the unclamped path performs NO sanitization,
        // so a NaN delta from a driver would be stored verbatim AND (because
        // `(NaN - x).abs() > EPS` is false) would not even mark the state dirty.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position_unclamped(DOM, node(0), pos(f32::NAN, f32::NAN), at(1));
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            off.x.is_nan() && off.y.is_nan(),
            "unclamped stores NaN as-is"
        );
        assert!(
            !m.has_pending_scroll_changes(),
            "a NaN write does not trip the dirty flag (NaN comparisons are false)"
        );
        // But a later re-registration re-clamps it back to a finite value.
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 500.0),
            at(2),
            16.0,
            16.0,
            false,
            true,
        );
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            !off.x.is_nan() && !off.y.is_nan(),
            "re-clamp must sanitize NaN"
        );
    }
    // ================================================== scroll_to / scroll_by
    // (numeric + animation lifecycle)
    #[test]
    fn scroll_to_zero_duration_is_immediate_for_both_clock_kinds() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 100.0),
            tick_dur(0),
            EasingFunction::Linear,
            at(1),
        );
        assert!(
            !m.has_active_animations(),
            "zero Tick duration must not animate"
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 100.0)));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 200.0),
            sys_dur(0, 0),
            EasingFunction::EaseOut,
            at(2),
        );
        assert!(
            !m.has_active_animations(),
            "zero System duration must not animate"
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 200.0)));
    }
    #[test]
    fn scroll_to_clamps_the_animation_target_not_just_the_final_offset() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 1e9),
            tick_dur(100),
            EasingFunction::Linear,
            at(0),
        );
        let anim_target = m
            .get_scroll_state(DOM, node(0))
            .and_then(|s| s.animation.as_ref())
            .map(|a| a.target_offset)
            .unwrap();
        assert_eq!(anim_target, pos(0.0, 400.0), "target must be pre-clamped");
        // Drive it to completion: the offset lands exactly on the clamped target.
        let r = m.tick(at(100));
        assert!(r.needs_repaint);
        assert_eq!(r.updated_nodes, vec![(DOM, node(0))]);
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
        assert!(!m.has_active_animations(), "animation must clear at t >= 1");
    }
    #[test]
    fn scroll_to_nan_target_animates_to_the_origin_never_to_nan() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 200.0), at(0));
        m.scroll_to(
            DOM,
            node(0),
            pos(f32::NAN, f32::NAN),
            tick_dur(10),
            EasingFunction::Linear,
            at(0),
        );
        m.tick(at(10));
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            !off.x.is_nan() && !off.y.is_nan(),
            "NaN target must be clamped away"
        );
        assert_eq!(off, LogicalPosition::zero());
    }
    #[test]
    fn scroll_by_accumulates_from_the_current_offset_and_saturates() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.scroll_by(
            DOM,
            node(0),
            pos(0.0, 100.0),
            tick_dur(0),
            EasingFunction::Linear,
            at(1),
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 100.0)));
        m.scroll_by(
            DOM,
            node(0),
            pos(0.0, 100.0),
            tick_dur(0),
            EasingFunction::Linear,
            at(2),
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 200.0)));
        // A delta big enough to overflow f32 arithmetic: saturates at max travel.
        m.scroll_by(
            DOM,
            node(0),
            pos(f32::MAX, f32::MAX),
            tick_dur(0),
            EasingFunction::Linear,
            at(3),
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
        // ...and back down past the origin.
        m.scroll_by(
            DOM,
            node(0),
            pos(f32::MIN, f32::MIN),
            tick_dur(0),
            EasingFunction::Linear,
            at(4),
        );
        assert_eq!(
            m.get_current_offset(DOM, node(0)),
            Some(LogicalPosition::zero())
        );
    }
    #[test]
    fn scroll_by_on_an_unknown_node_defaults_to_origin_and_stays_pinned() {
        let mut m = ScrollManager::new();
        m.scroll_by(
            DOM,
            node(7),
            pos(1e9, 1e9),
            tick_dur(0),
            EasingFunction::Linear,
            at(1),
        );
        // No bounds registered => max travel 0 => still at the origin, no panic.
        assert_eq!(
            m.get_current_offset(DOM, node(7)),
            Some(LogicalPosition::zero())
        );
    }
    #[test]
    fn scroll_by_nan_delta_does_not_poison_the_offset() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 100.0), at(0));
        m.scroll_by(
            DOM,
            node(0),
            pos(f32::NAN, f32::NAN),
            tick_dur(0),
            EasingFunction::Linear,
            at(1),
        );
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(!off.x.is_nan() && !off.y.is_nan());
        assert_eq!(off, LogicalPosition::zero(), "NaN target clamps to origin");
    }
    // =============================================================== tick()
    // (other: no_panic_smoke + animation invariants)
    #[test]
    fn tick_on_an_empty_manager_reports_no_work() {
        let mut m = ScrollManager::new();
        let r = m.tick(at(1));
        assert!(!r.needs_repaint);
        assert!(r.updated_nodes.is_empty());
    }
    #[test]
    fn tick_interpolates_linearly_and_completes_exactly_once() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 400.0),
            tick_dur(100),
            EasingFunction::Linear,
            at(0),
        );
        let r = m.tick(at(50));
        assert!(r.needs_repaint);
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 200.0)));
        assert!(m.has_active_animations(), "still mid-flight at t = 0.5");
        let r = m.tick(at(100));
        assert!(r.needs_repaint);
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
        assert!(!m.has_active_animations());
        // Ticking past the end must be a no-op, not a re-run.
        let r = m.tick(at(500));
        assert!(!r.needs_repaint);
        assert!(r.updated_nodes.is_empty());
    }
    #[test]
    fn tick_before_the_animation_start_time_saturates_to_zero_progress() {
        // `now` earlier than `start_time` => duration_since saturates to 0 =>
        // t = 0 => offset stays at start. No negative-progress overshoot.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 50.0), at(0));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 400.0),
            tick_dur(100),
            EasingFunction::Linear,
            at(100),
        );
        m.tick(at(0)); // clock went backwards
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 50.0)));
        assert!(m.has_active_animations(), "no progress => still animating");
    }
    #[test]
    fn tick_with_a_zero_duration_animation_completes_instead_of_producing_nan() {
        // 0/0 = NaN, but `NaN.min(1.0)` == 1.0 in Rust, so the animation snaps to
        // its target and is cleared — the offset never becomes NaN. (scroll_to
        // short-circuits zero durations; this covers a hand-built animation, e.g.
        // one whose duration was computed to zero.)
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.states.get_mut(&(DOM, node(0))).unwrap().animation = Some(ScrollAnimation {
            start_time: at(0),
            duration: tick_dur(0),
            start_offset: pos(0.0, 0.0),
            target_offset: pos(0.0, 300.0),
            easing: EasingFunction::Linear,
        });
        let r = m.tick(at(0));
        assert!(r.needs_repaint);
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(!off.y.is_nan(), "0/0 must not leak NaN into the offset");
        assert_eq!(off, pos(0.0, 300.0));
        assert!(!m.has_active_animations());
    }
    #[test]
    fn tick_with_a_mismatched_clock_kind_stalls_at_zero_instead_of_panicking() {
        // Tick-clock animation ticked by a System INSTANT. A System instant and a
        // Tick instant have no common origin, so `duration_since` has no
        // meaningful span to report and saturates to zero => t = 0 forever. The
        // animation never advances and never completes — but it does not panic or
        // corrupt the offset.
        //
        // Note this is specifically an INSTANT mismatch. A mismatch between the
        // elapsed DURATION's unit and the animation duration's unit is a
        // different thing entirely and does convert: `Duration::div` puts both on
        // a canonical nanosecond scale.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 25.0), at(0));
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 400.0),
            tick_dur(10),
            EasingFunction::Linear,
            at(0),
        );
        let r = m.tick(Instant::now()); // System clock vs Tick animation
        assert!(r.needs_repaint);
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 25.0)));
        assert!(
            m.has_active_animations(),
            "mismatched clocks stall the animation (t stays 0) — it never completes"
        );
    }
    #[test]
    fn tick_advances_every_animating_node_in_one_pass() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.register_or_update_scroll_node(
            DOM,
            node(1),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 300.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        m.scroll_to(
            DOM,
            node(0),
            pos(0.0, 400.0),
            tick_dur(10),
            EasingFunction::Linear,
            at(0),
        );
        m.scroll_to(
            DOM,
            node(1),
            pos(0.0, 200.0),
            tick_dur(10),
            EasingFunction::Linear,
            at(0),
        );
        let r = m.tick(at(10));
        assert_eq!(r.updated_nodes.len(), 2);
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
        assert_eq!(m.get_current_offset(DOM, node(1)), Some(pos(0.0, 200.0)));
    }
    // ============================================== register_or_update_scroll_node
    // (numeric: nan_inf / zero / min_max + no unbounded growth)
    #[test]
    fn register_twice_updates_in_place_and_keeps_the_offset() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 300.0), at(1));
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 500.0),
            at(2),
            16.0,
            16.0,
            false,
            true,
        );
        assert_eq!(
            m.debug_counts(),
            (1, 0),
            "re-register must not grow the map"
        );
        assert_eq!(
            m.get_current_offset(DOM, node(0)),
            Some(pos(0.0, 300.0)),
            "an existing node keeps its scroll offset across relayout"
        );
    }
    #[test]
    fn re_registering_with_shrunken_content_re_clamps_the_offset() {
        // The classic resize bug: content shrinks under a scrolled-to-bottom node.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 400.0), at(1));
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 150.0), // content shrank: max_y is now 50
            at(2),
            16.0,
            16.0,
            false,
            true,
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 50.0)));
    }
    #[test]
    fn register_with_non_finite_geometry_does_not_panic_or_leak_nan() {
        let mut m = ScrollManager::new();
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN),
            size(f32::NAN, f32::NAN),
            at(0),
            f32::NAN,
            f32::NAN,
            true,
            true,
        );
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            !off.x.is_nan() && !off.y.is_nan(),
            "NaN geometry must clamp to 0"
        );
        assert_eq!(off, LogicalPosition::zero());
        assert!(
            !m.is_node_scrollable(DOM, node(0)),
            "NaN overflow check is false"
        );
        m.register_or_update_scroll_node(
            DOM,
            node(1),
            rect(0.0, 0.0, f32::INFINITY, f32::INFINITY),
            size(f32::INFINITY, f32::INFINITY),
            at(0),
            f32::MAX,
            f32::MAX,
            true,
            true,
        );
        let off = m.get_current_offset(DOM, node(1)).unwrap();
        assert!(!off.x.is_nan() && !off.y.is_nan());
        assert_eq!(m.debug_counts(), (2, 0));
    }
    #[test]
    fn register_with_zero_sized_geometry_yields_a_non_scrollable_pinned_node() {
        let mut m = ScrollManager::new();
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            LogicalRect::zero(),
            LogicalSize::zero(),
            at(0),
            0.0,
            0.0,
            false,
            false,
        );
        assert!(!m.is_node_scrollable(DOM, node(0)));
        assert!(m.a11y_scroll_info(DOM, node(0)).is_none());
        let info = m.get_scroll_node_info(DOM, node(0)).unwrap();
        assert_eq!(info.max_scroll_x, 0.0);
        assert_eq!(info.max_scroll_y, 0.0);
    }
    // ===================================================== is_node_scrollable
    // (predicate: basic_true_false / edge_inputs)
    #[test]
    fn is_node_scrollable_is_strict_overflow_not_equality() {
        let mut m = ScrollManager::new();
        // Content exactly equal to the container: NOT scrollable (strict `>`).
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 100.0),
            at(0),
            16.0,
            16.0,
            false,
            false,
        );
        assert!(!m.is_node_scrollable(DOM, node(0)));
        // One extra pixel of height => scrollable.
        m.register_or_update_scroll_node(
            DOM,
            node(1),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 100.1),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        assert!(m.is_node_scrollable(DOM, node(1)));
        // Unknown node / unknown DOM => false, never a panic.
        assert!(!m.is_node_scrollable(DOM, node(999)));
        assert!(!m.is_node_scrollable(DOM1, node(1)));
    }
    #[test]
    fn is_node_scrollable_uses_the_virtual_size_when_present() {
        let mut m = ScrollManager::new();
        // Rendered content is tiny (only the visible slice), virtual content is huge.
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 50.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        assert!(!m.is_node_scrollable(DOM, node(0)));
        m.update_virtual_scroll_bounds(DOM, node(0), size(100.0, 100_000.0), None);
        assert!(
            m.is_node_scrollable(DOM, node(0)),
            "a VirtualView with a large virtual size must be scrollable"
        );
    }
    // ======================================================= can_consume_delta
    // (predicate: boundary / nan)
    #[test]
    fn can_consume_delta_respects_the_half_pixel_deadzone() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0)); // max_y = 400
        m.set_scroll_position(DOM, node(0), pos(0.0, 200.0), at(1));
        // |eff| <= EPS (0.5) is "not moved" on that axis.
        assert!(!m.can_consume_delta(DOM, node(0), 0.0, 0.0));
        assert!(
            !m.can_consume_delta(DOM, node(0), 0.5, 0.5),
            "exactly EPS is a no-move"
        );
        assert!(!m.can_consume_delta(DOM, node(0), -0.5, -0.5));
        assert!(m.can_consume_delta(DOM, node(0), 0.0, 0.51));
        assert!(m.can_consume_delta(DOM, node(0), 0.0, -0.51));
        // X has no travel at all (content width == container width).
        assert!(!m.can_consume_delta(DOM, node(0), 100.0, 0.0));
    }
    #[test]
    fn can_consume_delta_is_false_at_the_pinned_edges() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        // Pinned at the top: cannot go further up, can go down.
        m.set_scroll_position(DOM, node(0), pos(0.0, 0.0), at(1));
        assert!(!m.can_consume_delta(DOM, node(0), 0.0, -10.0));
        assert!(m.can_consume_delta(DOM, node(0), 0.0, 10.0));
        // Pinned at the bottom: the mirror image.
        m.set_scroll_position(DOM, node(0), pos(0.0, 400.0), at(2));
        assert!(!m.can_consume_delta(DOM, node(0), 0.0, 10.0));
        assert!(m.can_consume_delta(DOM, node(0), 0.0, -10.0));
    }
    #[test]
    fn can_consume_delta_rejects_nan_and_accepts_infinite_deltas() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 200.0), at(1));
        assert!(
            !m.can_consume_delta(DOM, node(0), f32::NAN, f32::NAN),
            "a NaN delta consumes nothing (every comparison is false)"
        );
        assert!(m.can_consume_delta(DOM, node(0), 0.0, f32::INFINITY));
        assert!(m.can_consume_delta(DOM, node(0), 0.0, f32::NEG_INFINITY));
        assert!(m.can_consume_delta(DOM, node(0), 0.0, f32::MAX));
        assert!(
            !m.can_consume_delta(DOM, node(999), 0.0, f32::MAX),
            "unknown node"
        );
    }
    // ======================================== map_wheel_onto_the_only_scrollable_axis
    #[test]
    fn a_vertical_wheel_scrolls_a_strip_that_can_only_move_horizontally() {
        // A page rail / tab bar / filmstrip. A mouse wheel has no horizontal
        // axis, so without this the strip cannot be scrolled by wheel at all.
        let m = mgr(size(100.0, 40.0), size(900.0, 40.0));
        assert_eq!(
            m.map_wheel_onto_the_only_scrollable_axis(DOM, node(0), 0.0, 30.0),
            (30.0, 0.0),
        );
    }
    #[test]
    fn a_box_that_scrolls_both_ways_keeps_the_axes_the_device_reported() {
        // Transposing here would make a vertical gesture pan sideways on any
        // ordinary two-way scroller — far worse than the dead strip it fixes.
        let m = mgr(size(100.0, 100.0), size(900.0, 900.0));
        assert_eq!(
            m.map_wheel_onto_the_only_scrollable_axis(DOM, node(0), 0.0, 30.0),
            (0.0, 30.0),
        );
    }
    #[test]
    fn a_real_horizontal_delta_is_never_rewritten() {
        // A trackpad swipe that already carries x must pass through untouched,
        // or a diagonal gesture would lose its vertical component.
        let m = mgr(size(100.0, 40.0), size(900.0, 40.0));
        assert_eq!(
            m.map_wheel_onto_the_only_scrollable_axis(DOM, node(0), -12.0, 30.0),
            (-12.0, 30.0),
        );
    }
    #[test]
    fn a_strip_with_nothing_to_scroll_is_left_alone() {
        // No travel on either axis: rewriting would hand the physics a delta
        // for an axis that cannot move, which reads as an overscroll bounce.
        let m = mgr(size(100.0, 40.0), size(100.0, 40.0));
        assert_eq!(
            m.map_wheel_onto_the_only_scrollable_axis(DOM, node(0), 0.0, 30.0),
            (0.0, 30.0),
        );
    }
    // ==================================================== select_scroll_target
    // (numeric: nan_inf / zero + fallback invariants)
    #[test]
    fn select_scroll_target_on_no_candidates_is_none() {
        let m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        assert!(m
            .select_scroll_target(core::iter::empty(), 0.0, 10.0)
            .is_none());
        // Candidates that are not scrollable are skipped entirely (no fallback).
        assert!(m
            .select_scroll_target([(DOM, node(50)), (DOM1, node(0))].into_iter(), 0.0, 10.0)
            .is_none());
    }
    #[test]
    fn select_scroll_target_with_zero_or_nan_delta_falls_back_to_the_innermost() {
        // Nothing "can consume" a zero/NaN delta, so the gesture still anchors on
        // the innermost scrollable node rather than being dropped.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.register_or_update_scroll_node(
            DOM,
            node(9),
            rect(0.0, 0.0, 50.0, 50.0),
            size(50.0, 200.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        let inner_first = [(DOM, node(9)), (DOM, node(0))];
        assert_eq!(
            m.select_scroll_target(inner_first.into_iter(), 0.0, 0.0),
            Some((DOM, node(9)))
        );
        assert_eq!(
            m.select_scroll_target(inner_first.into_iter(), f32::NAN, f32::NAN),
            Some((DOM, node(9)))
        );
        // An infinite delta IS consumable => also the innermost (it has room).
        assert_eq!(
            m.select_scroll_target(inner_first.into_iter(), 0.0, f32::INFINITY),
            Some((DOM, node(9)))
        );
    }
    // ======================================================= a11y_scroll_info
    // (other: no_panic_smoke)
    #[test]
    fn a11y_scroll_info_reports_travel_only_for_scrollable_nodes() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 120.0), at(1));
        let (off, max_x, max_y) = m.a11y_scroll_info(DOM, node(0)).unwrap();
        assert_eq!(off, pos(0.0, 120.0));
        assert_eq!(max_x, 0.0);
        assert_eq!(max_y, 400.0);
        // Non-scrollable node => None (screen readers must not offer scroll actions).
        m.register_or_update_scroll_node(
            DOM,
            node(1),
            rect(0.0, 0.0, 100.0, 100.0),
            size(10.0, 10.0),
            at(0),
            16.0,
            16.0,
            false,
            false,
        );
        assert!(m.a11y_scroll_info(DOM, node(1)).is_none());
        assert!(m.a11y_scroll_info(DOM, node(404)).is_none());
        assert!(m.a11y_scroll_info(DOM1, node(0)).is_none());
    }
    #[test]
    fn a11y_scroll_info_uses_the_virtual_size() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 100.0));
        assert!(m.a11y_scroll_info(DOM, node(0)).is_none());
        m.update_virtual_scroll_bounds(DOM, node(0), size(100.0, 1000.0), None);
        let (_, max_x, max_y) = m.a11y_scroll_info(DOM, node(0)).unwrap();
        assert_eq!(max_x, 0.0);
        assert_eq!(max_y, 900.0);
    }
    // ================================================== get_scroll_node_info
    // (other: no_panic_smoke — max_scroll is never negative)
    #[test]
    fn get_scroll_node_info_max_scroll_is_never_negative() {
        let m = mgr(size(500.0, 500.0), size(10.0, 10.0));
        let info = m.get_scroll_node_info(DOM, node(0)).unwrap();
        assert_eq!(
            info.max_scroll_x, 0.0,
            "underflow must clamp to 0, not go negative"
        );
        assert_eq!(info.max_scroll_y, 0.0);
        assert_eq!(info.current_offset, LogicalPosition::zero());
        assert!(m.get_scroll_node_info(DOM, node(1)).is_none());
    }
    #[test]
    fn get_scroll_node_info_prefers_the_virtual_size_for_max_travel() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 200.0));
        assert_eq!(
            m.get_scroll_node_info(DOM, node(0)).unwrap().max_scroll_y,
            100.0
        );
        m.update_virtual_scroll_bounds(DOM, node(0), size(600.0, 5000.0), Some(pos(1.0, 2.0)));
        let info = m.get_scroll_node_info(DOM, node(0)).unwrap();
        assert_eq!(info.max_scroll_x, 500.0);
        assert_eq!(info.max_scroll_y, 4900.0);
        // content_rect is still the *rendered* rect — the virtual size only moves
        // the bounds, it does not rewrite the layout geometry.
        assert_eq!(info.content_rect.size, size(100.0, 200.0));
    }
    // ============================================ update_virtual_scroll_bounds
    // (numeric: nan_inf / zero + implicit state creation)
    #[test]
    fn update_virtual_scroll_bounds_creates_a_state_for_an_unknown_node() {
        let mut m = ScrollManager::new();
        m.update_virtual_scroll_bounds(DOM, node(3), size(100.0, 9000.0), Some(pos(0.0, 4.0)));
        assert_eq!(m.debug_counts(), (1, 0));
        let s = m.get_scroll_state(DOM, node(3)).unwrap();
        assert_eq!(s.virtual_scroll_size, Some(size(100.0, 9000.0)));
        assert_eq!(s.virtual_scroll_offset, Some(pos(0.0, 4.0)));
        assert_eq!(s.current_offset, LogicalPosition::zero());
        // Container is still zero-sized, so all 9000px are reachable.
        assert!(m.is_node_scrollable(DOM, node(3)));
    }
    #[test]
    fn update_virtual_scroll_bounds_re_clamps_a_shrinking_virtual_size() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 100.0));
        m.update_virtual_scroll_bounds(DOM, node(0), size(100.0, 5000.0), None);
        m.set_scroll_position(DOM, node(0), pos(0.0, 4900.0), at(1));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 4900.0)));
        // The VirtualView shrinks (rows removed): the offset must follow it down.
        m.update_virtual_scroll_bounds(DOM, node(0), size(100.0, 300.0), None);
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 200.0)));
    }
    #[test]
    fn update_virtual_scroll_bounds_with_non_finite_size_does_not_panic() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 400.0), at(1));
        m.update_virtual_scroll_bounds(DOM, node(0), size(f32::NAN, f32::NAN), None);
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(!off.x.is_nan() && !off.y.is_nan());
        assert_eq!(
            off,
            LogicalPosition::zero(),
            "NaN virtual size => zero travel"
        );
        assert!(!m.is_node_scrollable(DOM, node(0)));
        m.update_virtual_scroll_bounds(DOM, node(0), size(0.0, f32::INFINITY), None);
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            !off.y.is_nan(),
            "infinite virtual height must not produce NaN"
        );
    }
    // ====================================================== update_node_bounds
    // (numeric: zero / negative / overflow / nan)
    #[test]
    fn update_node_bounds_creates_the_state_and_re_clamps_a_shrinking_content() {
        let mut m = ScrollManager::new();
        // Unknown node: the entry API materializes it at the scroll origin.
        m.update_node_bounds(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            rect(0.0, 0.0, 100.0, 500.0),
            at(0),
        );
        assert_eq!(m.debug_counts(), (1, 0));
        assert_eq!(
            m.get_current_offset(DOM, node(0)),
            Some(LogicalPosition::zero())
        );
        m.set_scroll_position(DOM, node(0), pos(0.0, 400.0), at(1));
        m.clear_scroll_dirty();
        // Content shrinks under a bottomed-out scroll: the offset must follow.
        m.update_node_bounds(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            rect(0.0, 0.0, 100.0, 150.0),
            at(2),
        );
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 50.0)));
        // NOTE: the forced re-clamp moved the offset by 350px but did NOT set the
        // dirty flag (unlike set_scroll_position) — pinning the real behavior.
        assert!(!m.has_pending_scroll_changes());
    }
    #[test]
    fn update_node_bounds_ignores_the_content_rect_origin() {
        // clamp() only reads `size`, so a content rect translated far away must
        // not shift the reachable travel.
        let mut m = ScrollManager::new();
        m.update_node_bounds(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            rect(999.0, 999.0, 100.0, 500.0),
            at(0),
        );
        m.set_scroll_position(DOM, node(0), pos(1e9, 1e9), at(1));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 400.0)));
    }
    #[test]
    fn update_node_bounds_with_non_finite_rects_does_not_leak_nan() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 400.0), at(1));
        m.update_node_bounds(
            DOM,
            node(0),
            rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN),
            rect(f32::NAN, f32::NAN, f32::NAN, f32::NAN),
            at(2),
        );
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(
            !off.x.is_nan() && !off.y.is_nan(),
            "NaN bounds must clamp to 0"
        );
        assert_eq!(off, LogicalPosition::zero());
        // Infinite content: the offset stays finite (clamped to the old value).
        m.update_node_bounds(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            rect(0.0, 0.0, f32::INFINITY, f32::INFINITY),
            at(3),
        );
        let off = m.get_current_offset(DOM, node(0)).unwrap();
        assert!(off.x.is_finite() && off.y.is_finite());
    }
    // ============================================ get_scroll_states_for_dom /
    //                                              build_scroll_offset_map
    // (other: no_panic_smoke + DOM isolation)
    #[test]
    fn get_scroll_states_for_dom_filters_by_dom_and_reports_the_live_offset() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 42.0), at(1));
        m.register_or_update_scroll_node(
            DOM1,
            node(0),
            rect(0.0, 0.0, 10.0, 10.0),
            size(10.0, 100.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        let states = m.get_scroll_states_for_dom(DOM);
        assert_eq!(states.len(), 1, "other DOMs must not leak in");
        let sp = states.get(&node(0)).unwrap();
        assert_eq!(sp.parent_rect, rect(0.0, 0.0, 100.0, 100.0));
        assert_eq!(sp.children_rect.origin, pos(0.0, 42.0));
        assert_eq!(sp.children_rect.size, size(100.0, 500.0));
        // A DOM with no registered nodes returns an empty map, not a panic.
        assert!(m.get_scroll_states_for_dom(DomId { inner: 99 }).is_empty());
    }
    #[test]
    fn get_scroll_states_for_dom_uses_the_virtual_size_as_children_rect() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 120.0));
        m.update_virtual_scroll_bounds(DOM, node(0), size(100.0, 8000.0), None);
        let states = m.get_scroll_states_for_dom(DOM);
        assert_eq!(
            states.get(&node(0)).unwrap().children_rect.size,
            size(100.0, 8000.0)
        );
    }
    /// CONVENTION PIN, end to end: `children_rect.origin` is the raw scroll
    /// offset in a space of its own, and `parent_rect.origin` is an absolute
    /// window coordinate. Every fixture above registers its container at
    /// (0, 0), where the two candidate conventions are indistinguishable —
    /// this one puts the container where the AzWriter document view actually
    /// sits (below the ribbon, indented from the left) and drives the reported
    /// offset through the SAME geometry function the scrollbar painter and the
    /// GPU-only scroll path use.
    ///
    /// The consumers used to compute `children_rect.origin - parent_rect.origin`.
    /// For the vertical leg below that made an UNSCROLLED container report
    /// -120, which `compute_thumb_geometry` then took by absolute value (an
    /// `.abs()` since removed — see
    /// `a_negative_overscroll_offset_pins_the_thumb_to_the_start_of_the_track`)
    /// — +120 is 15% of the 800px scroll range, so the thumb opened 38.4px
    /// down its own track instead of at the top.
    #[test]
    fn scroll_states_of_a_container_below_the_window_origin_drive_the_thumb_from_zero() {
        use crate::solver3::scrollbar::{
            compute_scrollbar_geometry_with_button_size, ScrollbarGeometry,
        };
        const THICKNESS: f32 = 16.0;
        // A 300x400 viewport at absolute (250, 120) over 900x1200 of content:
        // max scroll is (600, 800) on the two axes.
        let mut m = ScrollManager::new();
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(250.0, 120.0, 300.0, 400.0),
            size(900.0, 1200.0),
            at(0),
            THICKNESS,
            THICKNESS,
            true,
            true,
        );
        // Exactly what `paint_scrollbars` does: read the state, take the offset
        // straight out of `children_rect.origin`, feed it to the shared geometry.
        fn geom(
            m: &ScrollManager,
            expected_offset: LogicalPosition,
            orientation: ScrollbarOrientation,
        ) -> ScrollbarGeometry {
            let sp = *m.get_scroll_states_for_dom(DOM).get(&node(0)).unwrap();
            assert_eq!(
                sp.parent_rect.origin,
                pos(250.0, 120.0),
                "parent_rect keeps the ABSOLUTE container position"
            );
            assert_eq!(
                sp.children_rect.origin, expected_offset,
                "children_rect.origin is the raw offset, never container-relative"
            );
            compute_scrollbar_geometry_with_button_size(
                orientation,
                sp.parent_rect,
                sp.children_rect.size,
                match orientation {
                    ScrollbarOrientation::Vertical => sp.children_rect.origin.y,
                    ScrollbarOrientation::Horizontal => sp.children_rect.origin.x,
                },
                THICKNESS,
                true,
                0.0,
            )
        }
        // --- unscrolled: the thumb sits at the very top / far left ----------
        let v = geom(&m, pos(0.0, 0.0), ScrollbarOrientation::Vertical);
        assert_eq!(
            v.thumb_offset, 0.0,
            "was 38.4 with the mixed-origin subtraction"
        );
        let h = geom(&m, pos(0.0, 0.0), ScrollbarOrientation::Horizontal);
        assert_eq!(
            h.thumb_offset, 0.0,
            "was ~78.9 with the mixed-origin subtraction"
        );
        // --- half way: half of the thumb's travel ---------------------------
        m.set_scroll_position(DOM, node(0), pos(300.0, 400.0), at(1));
        let v = geom(&m, pos(300.0, 400.0), ScrollbarOrientation::Vertical);
        let expected = (v.usable_track_length - v.thumb_length) * 0.5;
        assert!((v.thumb_offset - expected).abs() < 1e-3, "{v:?}");
        let h = geom(&m, pos(300.0, 400.0), ScrollbarOrientation::Horizontal);
        let expected = (h.usable_track_length - h.thumb_length) * 0.5;
        assert!((h.thumb_offset - expected).abs() < 1e-3, "{h:?}");
        // --- bottomed out: the thumb ends flush with the track --------------
        m.set_scroll_position(DOM, node(0), pos(9_999.0, 9_999.0), at(2));
        let v = geom(&m, pos(600.0, 800.0), ScrollbarOrientation::Vertical);
        assert!(
            (v.thumb_offset - (v.usable_track_length - v.thumb_length)).abs() < 1e-3,
            "{v:?}"
        );
        let h = geom(&m, pos(600.0, 800.0), ScrollbarOrientation::Horizontal);
        assert!(
            (h.thumb_offset - (h.usable_track_length - h.thumb_length)).abs() < 1e-3,
            "{h:?}"
        );
    }
    #[test]
    fn build_scroll_offset_map_only_emits_nodes_present_in_scroll_ids() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 25.0), at(1));
        m.register_or_update_scroll_node(
            DOM,
            node(4),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 500.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        m.register_or_update_scroll_node(
            DOM1,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 500.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        // Empty id map => empty offset map (and no panic).
        assert!(m.build_scroll_offset_map(DOM, &HashMap::new()).is_empty());
        let mut ids: HashMap<u64, NodeId> = HashMap::new();
        ids.insert(100, node(0)); // scroll id 100 -> DOM node 0
        ids.insert(700, node(7)); // an id for a node that has no scroll state
        let map = m.build_scroll_offset_map(DOM, &ids);
        assert_eq!(
            map.len(),
            1,
            "node 4 has no scroll_id; DOM1 is a different dom"
        );
        assert_eq!(map.get(&100), Some(&(0.0, 25.0)));
        assert!(!map.contains_key(&700));
    }
    #[test]
    fn build_scroll_offset_map_resolves_a_scroller_whose_layout_index_diverges() {
        // REGRESSION, CPU present path: "the wheel moves the thumb but the
        // content stays frozen".
        //
        // The offset map used to be built by indexing the layout-index-keyed
        // `scroll_ids` table with `node_id.index()`. That holds only for DOMs
        // whose layout tree happens to be index-identical to the DOM — which
        // is exactly what the minimal fixtures above are, and why nothing
        // caught it. A text run ahead of the scroll container makes layout
        // insert anonymous boxes, the indices diverge, the lookup misses, the
        // compositor resolves the layer offset as (0,0) and the scroll-shift
        // machinery sees no delta. The thumb keeps moving because it rides the
        // (DomId, NodeId)-keyed GPU value cache, which never had the bug.
        //
        // The tables below are shaped exactly as `LayoutWindow::compute_scroll_ids`
        // emits them for such a tree: the root scroller is DOM node 0 at layout
        // index 0, the content scroller is DOM node 2 sitting at layout index 5.
        let mut m = mgr(size(200.0, 200.0), size(200.0, 400.0));
        m.register_or_update_scroll_node(
            DOM,
            node(2),
            rect(0.0, 0.0, 200.0, 200.0),
            size(200.0, 2000.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        m.set_scroll_position(DOM, node(2), pos(0.0, 300.0), at(1));
        let mut scroll_ids: HashMap<LayoutNodeId, u64> = HashMap::new();
        scroll_ids.insert(LayoutNodeId::new(0), 100);
        scroll_ids.insert(LayoutNodeId::new(5), 500);
        let mut scroll_id_to_node_id: HashMap<u64, NodeId> = HashMap::new();
        scroll_id_to_node_id.insert(100, node(0));
        scroll_id_to_node_id.insert(500, node(2));
        // The premise, asserted rather than assumed: for this tree the DOM
        // NodeId is NOT a valid key into the layout-index table. Note the
        // deliberate cross-space cast: since `LayoutNodeId` landed, this
        // probe is the ONLY way to even ask the question — the conflation
        // this test guards against no longer type-checks in production code.
        assert!(
            !scroll_ids.contains_key(&LayoutNodeId::new(node(2).index())),
            "fixture must actually diverge, otherwise it re-tests the coinciding case"
        );
        let map = m.build_scroll_offset_map(DOM, &scroll_id_to_node_id);
        assert_eq!(
            map.get(&500),
            Some(&(0.0, 300.0)),
            "the scrolled container must reach the renderer, or its content freezes"
        );
        assert_eq!(
            map.get(&100),
            Some(&(0.0, 0.0)),
            "the unscrolled root still reports (0,0)"
        );
    }
    // ====================================================== find_scroll_parent
    // (other: no_panic_smoke)
    #[test]
    fn find_scroll_parent_walks_up_to_the_nearest_registered_ancestor() {
        // hierarchy: 0 (root) <- 1 <- 2  (parent field is 1-based encoded)
        let hierarchy = [
            NodeHierarchyItem {
                parent: 0,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 2,
            },
            NodeHierarchyItem {
                parent: 1,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 3,
            },
            NodeHierarchyItem {
                parent: 2,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
        ];
        let m = mgr(size(100.0, 100.0), size(100.0, 500.0)); // node 0 registered
        for incl in [Inclusivity::AncestorsOnly, Inclusivity::SelfAndAncestors] {
            assert_eq!(
                m.find_scroll_parent(DOM, node(2), &hierarchy, incl),
                Some(node(0)),
                "must skip the unregistered node 1 and find the root scroll container"
            );
            // No scroll container anywhere in this DOM.
            assert_eq!(m.find_scroll_parent(DOM1, node(2), &hierarchy, incl), None);
        }
    }
    #[test]
    fn find_scroll_parent_inclusivity_decides_whether_the_node_answers_itself() {
        // REGRESSION: this was hardcoded to ancestors-only, so "which scroll
        // box does this node live in?" could never answer "this one" — which
        // is why drag-autoscroll inside an overflowing TextInput scrolled the
        // PAGE instead of the field (the caret's node IS the scroll box).
        let hierarchy = [
            NodeHierarchyItem {
                parent: 0,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 2,
            },
            NodeHierarchyItem {
                parent: 1,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
        ];
        let m = mgr(size(100.0, 100.0), size(100.0, 500.0)); // node 0 registered
        assert_eq!(
            m.find_scroll_parent(DOM, node(0), &hierarchy, Inclusivity::SelfAndAncestors),
            Some(node(0)),
            "a registered node IS its own scroll box"
        );
        assert_eq!(
            m.find_scroll_parent(DOM, node(0), &hierarchy, Inclusivity::AncestorsOnly),
            None,
            "...but never the container to CHAIN to"
        );
    }
    #[test]
    fn find_scroll_parent_handles_empty_and_out_of_range_hierarchies() {
        let m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        for incl in [Inclusivity::AncestorsOnly, Inclusivity::SelfAndAncestors] {
            // Empty slice: the budget is 0 => None, no index panic.
            assert_eq!(m.find_scroll_parent(DOM, node(0), &[], incl), None);
            assert_eq!(m.find_scroll_parent(DOM, node(9999), &[], incl), None);
            // Node id past the end of the hierarchy: still no panic.
            let hierarchy = [NodeHierarchyItem::zeroed()];
            assert_eq!(
                m.find_scroll_parent(DOM, node(9999), &hierarchy, incl),
                None
            );
        }
    }
    #[test]
    fn find_scroll_parent_terminates_on_a_cyclic_hierarchy() {
        // 0 -> 1 -> 0 (parent is 1-based encoded, so `parent: 2` means node 1).
        let hierarchy = [
            NodeHierarchyItem {
                parent: 2,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
            NodeHierarchyItem {
                parent: 1,
                previous_sibling: 0,
                next_sibling: 0,
                last_child: 0,
            },
        ];
        let m = ScrollManager::new();
        assert_eq!(
            m.find_scroll_parent(DOM, node(0), &hierarchy, Inclusivity::AncestorsOnly),
            None
        );
    }
    // ============================================== calculate_scrollbar_states
    // (other: no_panic_smoke + no unbounded growth)
    #[test]
    fn calculate_scrollbar_states_is_idempotent_and_only_for_overflowing_axes() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.calculate_scrollbar_states();
        assert_eq!(m.debug_counts(), (1, 1), "only the vertical axis overflows");
        assert!(m
            .get_scrollbar_state(DOM, node(0), ScrollbarOrientation::Vertical)
            .is_some());
        assert!(m
            .get_scrollbar_state(DOM, node(0), ScrollbarOrientation::Horizontal)
            .is_none());
        // Re-running each frame must clear first — otherwise the map grows forever.
        for _ in 0..10 {
            m.calculate_scrollbar_states();
        }
        assert_eq!(
            m.debug_counts(),
            (1, 1),
            "per-frame recompute must not accumulate"
        );
        assert_eq!(m.iter_scrollbar_states().count(), 1);
    }
    #[test]
    fn calculate_scrollbar_states_drops_bars_once_the_content_fits() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.calculate_scrollbar_states();
        assert_eq!(m.debug_counts().1, 1);
        // Relayout: content now fits => the scrollbar must disappear.
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 50.0),
            at(1),
            16.0,
            16.0,
            false,
            false,
        );
        m.calculate_scrollbar_states();
        assert_eq!(m.debug_counts().1, 0);
        assert!(m.hit_test_scrollbars(pos(90.0, 50.0)).is_none());
    }
    #[test]
    fn calculate_scrollbar_states_produces_finite_geometry_for_both_axes() {
        let mut m = ScrollManager::new();
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(1000.0, 1000.0),
            at(0),
            16.0,
            16.0,
            true,
            true,
        );
        m.calculate_scrollbar_states();
        assert_eq!(m.debug_counts(), (1, 2), "both axes overflow");
        for (_, sb) in m.iter_scrollbar_states() {
            assert!(sb.visible);
            assert!(sb.base_size.is_finite() && sb.base_size > 0.0);
            assert!(sb.scale.x.is_finite() && sb.scale.y.is_finite());
            assert!(sb.thumb_length.is_finite());
            assert!(sb.thumb_offset.is_finite());
            assert!(sb.usable_track_length.is_finite());
            assert!(sb.track_rect.size.width.is_finite());
            assert!(sb.track_rect.size.height.is_finite());
        }
    }
    #[test]
    fn calculate_scrollbar_states_zero_thickness_falls_back_to_the_default_width() {
        // An overlay scrollbar reports thickness 0 from layout; the geometry must
        // still divide by a non-zero width (otherwise `scale` becomes inf/NaN).
        let mut m = ScrollManager::new();
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 400.0),
            at(0),
            0.0, // scrollbar_thickness (overlay)
            0.0, // visual_width_px
            false,
            true,
        );
        m.calculate_scrollbar_states();
        let sb = m
            .get_scrollbar_state(DOM, node(0), ScrollbarOrientation::Vertical)
            .unwrap();
        assert_eq!(sb.base_size, crate::solver3::fc::DEFAULT_SCROLLBAR_WIDTH_PX);
        assert_eq!(
            sb.button_size, 0.0,
            "overlay scrollbars have no arrow buttons"
        );
        assert!(
            sb.scale.x.is_finite() && sb.scale.y.is_finite(),
            "no div-by-zero"
        );
    }
    #[test]
    fn calculate_scrollbar_state_from_geometry_survives_nan_input() {
        let mut s = state(size(f32::NAN, f32::NAN), size(f32::NAN, f32::NAN));
        s.scrollbar_thickness = f32::NAN;
        s.visual_width_px = f32::NAN;
        // `NaN > 0.0` is false for both width sources, so it falls back to the
        // default width instead of dividing by NaN.
        let sb = ScrollManager::calculate_scrollbar_state_from_geometry(
            &s,
            ScrollbarOrientation::Vertical,
        );
        assert!(sb.visible);
        assert_eq!(sb.base_size, crate::solver3::fc::DEFAULT_SCROLLBAR_WIDTH_PX);
        // `.max(0.0)` rescues every length: NaN geometry degrades to a zero-length
        // thumb on a zero-length track rather than propagating NaN.
        assert_eq!(sb.usable_track_length, 0.0);
        assert_eq!(sb.thumb_length, 0.0);
        assert_eq!(sb.thumb_offset, 0.0);
        assert_eq!(sb.thumb_position_ratio, 0.0);
        // The lengths are safe, but `scale` divides the (NaN) track height by the
        // thickness with no rescue — a NaN scale reaches the render transform.
        assert!(
            sb.scale.y.is_nan(),
            "NaN container height still leaks into ScrollbarState::scale"
        );
        // Hit-testing such a bar is still total: y < button_size wins first.
        assert_eq!(
            sb.hit_test_component(pos(0.0, 5.0)),
            ScrollbarComponent::TopButton
        );
    }
    // ================================== hit_test_scrollbar / hit_test_scrollbars
    // (numeric: zero / negative / nan_inf)
    #[test]
    fn hit_test_scrollbars_finds_the_vertical_bar_and_reports_local_coords() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.calculate_scrollbar_states();
        // Track is the right-hand 16px strip: origin.x = 100 - 16 = 84.
        let hit = m
            .hit_test_scrollbars(pos(90.0, 50.0))
            .expect("inside the track");
        assert_eq!(hit.dom_id, DOM);
        assert_eq!(hit.node_id, node(0));
        assert_eq!(hit.orientation, ScrollbarOrientation::Vertical);
        assert_eq!(hit.global_position, pos(90.0, 50.0));
        assert_eq!(
            hit.local_position,
            pos(6.0, 50.0),
            "local = global - track origin"
        );
        // Just outside the track (content area) => no hit.
        assert!(m.hit_test_scrollbars(pos(10.0, 50.0)).is_none());
        // Same answer through the node-targeted entry point.
        let hit2 = m.hit_test_scrollbar(DOM, node(0), pos(90.0, 50.0)).unwrap();
        assert_eq!(hit2.local_position, hit.local_position);
        assert_eq!(hit2.component, hit.component);
        assert!(m
            .hit_test_scrollbar(DOM, node(1), pos(90.0, 50.0))
            .is_none());
    }
    #[test]
    fn hit_test_scrollbars_rejects_non_finite_and_out_of_range_positions() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.calculate_scrollbar_states();
        for p in [
            pos(f32::NAN, f32::NAN),
            pos(f32::INFINITY, f32::INFINITY),
            pos(f32::NEG_INFINITY, f32::NEG_INFINITY),
            pos(f32::MAX, f32::MAX),
            pos(f32::MIN, f32::MIN),
            pos(-1.0, -1.0),
            pos(0.0, 0.0),
        ] {
            assert!(
                m.hit_test_scrollbars(p).is_none(),
                "position {p:?} must not hit the 84..100 x 0..100 track"
            );
            assert!(m.hit_test_scrollbar(DOM, node(0), p).is_none());
        }
    }
    #[test]
    fn hit_test_scrollbars_before_calculate_returns_none() {
        // The states map is only filled by calculate_scrollbar_states(); querying
        // first must be a clean miss, not a stale hit.
        let m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        assert!(m.hit_test_scrollbars(pos(90.0, 50.0)).is_none());
        assert!(m
            .hit_test_scrollbar(DOM, node(0), pos(90.0, 50.0))
            .is_none());
    }
    #[test]
    fn hit_test_scrollbars_skips_invisible_bars() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.calculate_scrollbar_states();
        m.scrollbar_states
            .get_mut(&(DOM, node(0), ScrollbarOrientation::Vertical))
            .unwrap()
            .visible = false;
        assert!(m.hit_test_scrollbars(pos(90.0, 50.0)).is_none());
        assert!(m
            .hit_test_scrollbar(DOM, node(0), pos(90.0, 50.0))
            .is_none());
    }
    // ========================================================= input recording
    // (record_scroll_input / record_scroll_from_hit_test)
    #[test]
    fn record_scroll_input_reports_start_timer_only_on_the_first_pending_event() {
        let mut m = ScrollManager::new();
        assert!(
            m.record_scroll_input(input(0.0, 1.0, 1)),
            "queue was empty => start"
        );
        assert!(
            !m.record_scroll_input(input(0.0, 1.0, 2)),
            "timer already running"
        );
        let _ = m.get_input_queue().take_all();
        assert!(
            m.record_scroll_input(input(0.0, 1.0, 3)),
            "drained => start again"
        );
    }
    #[test]
    fn record_scroll_input_applies_the_sign_to_extreme_deltas_without_overflow() {
        let mut m = ScrollManager::new();
        m.record_scroll_input(input(f32::MAX, f32::INFINITY, 1));
        m.record_scroll_input(input(f32::NAN, f32::MIN, 2));
        let q = m.get_input_queue().take_all();
        assert_eq!(q[0].delta.x, -f32::MAX, "sign flip must not overflow");
        assert_eq!(q[0].delta.y, f32::NEG_INFINITY);
        assert!(q[1].delta.x.is_nan(), "NaN * -1 stays NaN, no panic");
        assert_eq!(q[1].delta.y, f32::MAX);
    }
    #[test]
    fn record_scroll_from_hit_test_records_the_wheel_delta_even_with_no_hover() {
        // The wheel-as-zoom widgets (e.g. the map) depend on pending_wheel_event
        // being set unconditionally — before the hit-test lookup can bail out.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        let hover = HoverManager::new(); // no hit-test recorded at all
        let out = m.record_scroll_from_hit_test_test_shim(
            3.0,
            -7.0,
            ScrollInputSource::WheelDiscrete,
            &hover,
            &InputPointId::Mouse,
            at(1),
        );
        assert!(out.is_none(), "no hover => no scroll target");
        assert_eq!(
            m.pending_wheel_event,
            Some(pos(3.0, -7.0)),
            "raw delta is recorded"
        );
        assert!(
            !m.get_input_queue().has_pending(),
            "nothing queued for physics"
        );
    }
    #[test]
    fn record_scroll_from_hit_test_queues_the_raw_delta_and_signals_the_timer() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        let hover = hover_over(&[0]);
        let (dom_id, node_id, start_timer) = m
            .record_scroll_from_hit_test_test_shim(
                0.0,
                -10.0, // raw "wheel down" under the traditional sign
                ScrollInputSource::WheelDiscrete,
                &hover,
                &InputPointId::Mouse,
                at(1),
            )
            .expect("node 0 is scrollable and under the cursor");
        assert_eq!((dom_id, node_id), (DOM, node(0)));
        assert!(
            start_timer,
            "first queued input must start the physics timer"
        );
        assert_eq!(m.pending_wheel_event, Some(pos(0.0, -10.0)));
        // A second event while the queue is still pending must NOT re-start it.
        let (_, _, start_again) = m
            .record_scroll_from_hit_test_test_shim(
                0.0,
                -10.0,
                ScrollInputSource::WheelDiscrete,
                &hover,
                &InputPointId::Mouse,
                at(2),
            )
            .unwrap();
        assert!(!start_again);
        let q = m.get_input_queue().take_all();
        assert_eq!(q.len(), 2);
        // scroll_sign() is applied exactly once, in record_scroll_input.
        assert_eq!(q[0].delta.y, 10.0, "raw -10 * traditional sign (-1) = +10");
        assert_eq!(q[0].source, ScrollInputSource::WheelDiscrete);
        assert_eq!(q[0].timestamp, at(1));
    }
    #[test]
    fn record_scroll_from_hit_test_ignores_hovered_nodes_that_cannot_scroll() {
        let mut m = ScrollManager::new();
        // Registered, but the content fits => not scrollable.
        m.register_or_update_scroll_node(
            DOM,
            node(0),
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 100.0),
            at(0),
            16.0,
            16.0,
            false,
            false,
        );
        let hover = hover_over(&[0]);
        let out = m.record_scroll_from_hit_test_test_shim(
            0.0,
            -10.0,
            ScrollInputSource::WheelDiscrete,
            &hover,
            &InputPointId::Mouse,
            at(1),
        );
        assert!(
            out.is_none(),
            "a non-overflowing node must not swallow the wheel"
        );
        assert_eq!(m.pending_wheel_event, Some(pos(0.0, -10.0)));
        assert!(!m.get_input_queue().has_pending());
    }
    #[test]
    fn record_scroll_from_hit_test_with_non_finite_deltas_does_not_panic() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        let hover = hover_over(&[0]);
        // NaN: nothing can consume it, so the innermost scrollable is the fallback.
        let out = m.record_scroll_from_hit_test_test_shim(
            f32::NAN,
            f32::NAN,
            ScrollInputSource::TrackpadContinuous,
            &hover,
            &InputPointId::Mouse,
            at(1),
        );
        assert_eq!(out.map(|(d, n, _)| (d, n)), Some((DOM, node(0))));
        assert!(m.pending_wheel_event.unwrap().x.is_nan());
        let q = m.get_input_queue().take_all();
        assert_eq!(q.len(), 1);
        assert!(q[0].delta.x.is_nan(), "NaN is queued verbatim, no panic");
        // Infinity: consumable (there is room), still queued safely.
        let out = m.record_scroll_from_hit_test_test_shim(
            0.0,
            f32::NEG_INFINITY,
            ScrollInputSource::WheelDiscrete,
            &hover,
            &InputPointId::Mouse,
            at(2),
        );
        assert!(out.is_some());
        let q = m.get_input_queue().take_all();
        assert_eq!(q[0].delta.y, f32::INFINITY, "-inf * -1 = +inf");
    }
    #[test]
    fn record_scroll_from_hit_test_picks_the_innermost_scrollable_under_the_cursor() {
        // Both nodes are hovered; scroll_hit_test_nodes is walked in reverse key
        // order, so the higher (deeper) NodeId wins when it can consume the delta.
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.register_or_update_scroll_node(
            DOM,
            node(5),
            rect(0.0, 0.0, 50.0, 50.0),
            size(50.0, 200.0),
            at(0),
            16.0,
            16.0,
            false,
            true,
        );
        let hover = hover_over(&[0, 5]);
        let (_, node_id, _) = m
            .record_scroll_from_hit_test_test_shim(
                0.0,
                -10.0,
                ScrollInputSource::WheelDiscrete,
                &hover,
                &InputPointId::Mouse,
                at(1),
            )
            .unwrap();
        assert_eq!(node_id, node(5), "innermost (deepest) scrollable wins");
    }
    // ============================================================ getters
    // (get_current_offset / get_last_activity_time / get_scroll_state)
    #[test]
    fn getters_agree_with_the_recorded_state() {
        let mut m = mgr(size(100.0, 100.0), size(100.0, 500.0));
        m.set_scroll_position(DOM, node(0), pos(0.0, 33.0), at(7));
        assert_eq!(m.get_current_offset(DOM, node(0)), Some(pos(0.0, 33.0)));
        assert_eq!(m.get_last_activity_time(DOM, node(0)), Some(at(7)));
        let s = m.get_scroll_state(DOM, node(0)).unwrap();
        assert_eq!(s.current_offset, pos(0.0, 33.0));
        assert!(s.animation.is_none());
        // Unknown keys are a clean miss on every getter.
        assert!(m.get_current_offset(DOM1, node(0)).is_none());
        assert!(m.get_last_activity_time(DOM, node(1)).is_none());
        assert!(m.get_scroll_state(DOM1, node(1)).is_none());
    }
    #[test]
    fn get_input_queue_hands_out_a_shared_handle() {
        let mut m = ScrollManager::new();
        let q = m.get_input_queue();
        assert!(!q.has_pending());
        m.record_scroll_input(input(0.0, 1.0, 1));
        assert!(
            q.has_pending(),
            "the handle must observe pushes made by the manager"
        );
        assert_eq!(q.take_all().len(), 1);
        assert!(
            !m.get_input_queue().has_pending(),
            "draining the handle drains the manager's queue"
        );
    }
}
#[cfg(all(test, feature = "std"))]
impl ScrollManager {
    /// Test shim: the old 6-arg call shape with `device = TestDriver`.
7
    pub(crate) fn record_scroll_from_hit_test_test_shim(
7
        &mut self,
7
        delta_x: f32,
7
        delta_y: f32,
7
        source: ScrollInputSource,
7
        hover_manager: &crate::managers::hover::HoverManager,
7
        input_point_id: &InputPointId,
7
        now: Instant,
7
    ) -> Option<(DomId, NodeId, bool)> {
7
        self.record_scroll_from_hit_test(
7
            delta_x,
7
            delta_y,
7
            source,
7
            ScrollInputDevice::TestDriver,
7
            hover_manager,
7
            input_point_id,
7
            now,
        )
7
    }
}
impl ScrollManager {
    /// Fold one scroll input's source into the gesture latch, recording a
    /// `Started` / `Ended` transition when the gesture actually turns over.
    ///
    /// Called from the platform scroll paths and the physics timer. The source
    /// classification already exists on every backend; this only decides when
    /// it crosses a boundary:
    ///
    /// - `TrackpadEnd` is the explicit end-of-gesture signal. macOS derives it from
    ///   `NSEvent.phase`/`momentumPhase` being `Ended`/`Cancelled`, and Wayland synthesizes it from
    ///   `wl_pointer.axis_stop`. It carries a ZERO delta, which is exactly why it must not be gated
    ///   behind a delta threshold.
    /// - `TrackpadMomentum` is still the same gesture: the fingers are up, but the OS is playing
    ///   out a canned tail. Ending on the finger lift would fire `ScrollEnd` while the content is
    ///   visibly still moving.
    /// - `Programmatic` and `AnimateTo` are not user gestures and never open or close one.
12
    pub fn note_scroll_phase(&mut self, source: ScrollInputSource) {
12
        match source {
2
            ScrollInputSource::Programmatic | ScrollInputSource::AnimateTo => {}
            ScrollInputSource::TrackpadEnd => {
                if self.scroll_gesture_active {
                    self.scroll_gesture_active = false;
                    self.pending_scroll_phase.push(ScrollPhaseTransition::Ended);
                }
            }
            ScrollInputSource::TrackpadContinuous
            | ScrollInputSource::TrackpadMomentum
            | ScrollInputSource::WheelDiscrete => {
10
                if !self.scroll_gesture_active {
7
                    self.scroll_gesture_active = true;
7
                    self.pending_scroll_phase
7
                        .push(ScrollPhaseTransition::Started);
7
                }
            }
        }
12
    }
    /// Close an open gesture that no input will close for us.
    ///
    /// A discrete wheel has no end-of-gesture signal at all — there is no
    /// "finger lift" for a ratcheting wheel — so a `WheelDiscrete` gesture
    /// would otherwise stay open forever and never fire `ScrollEnd`. The
    /// physics timer calls this when the scroll velocity settles.
3
    pub fn settle_scroll_gesture(&mut self) {
3
        if self.scroll_gesture_active {
1
            self.scroll_gesture_active = false;
1
            self.pending_scroll_phase.push(ScrollPhaseTransition::Ended);
2
        }
3
    }
}
impl azul_core::events::EventProvider for ScrollManager {
    /// Yield `ScrollStart` / `ScrollEnd` for each phase transition observed
    /// since the last drain.
    ///
    /// Window-level (target = root): a gesture belongs to the window, not to
    /// whichever node happened to be under the cursor when it started — the
    /// pointer can leave that node mid-flick. Planning names the Hover, Focus
    /// and Window variants for both types, so a node-level listener still
    /// receives them by propagation.
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
        self.pending_scroll_phase
            .iter()
            .map(|t| {
                let event_type = match t {
                    ScrollPhaseTransition::Started => EventType::ScrollStart,
                    ScrollPhaseTransition::Ended => EventType::ScrollEnd,
                };
                SyntheticEvent::new(
                    event_type,
                    azul_core::events::EventSource::User,
                    DomNodeId::ROOT,
                    timestamp.clone(),
                    EventData::None,
                )
            })
            .collect()
    }
}