1
//! Scroll-into-view implementation
2
//!
3
//! Provides W3C CSSOM View Module compliant scroll-into-view functionality.
4
//! This module contains the core primitive `scroll_rect_into_view` which all
5
//! higher-level scroll-into-view APIs build upon.
6
//!
7
//! # Architecture
8
//!
9
//! The core principle is that all scroll-into-view operations reduce to scrolling
10
//! a rectangle into the visible area of its scroll container ancestry:
11
//!
12
//! - `scroll_rect_into_view`: Core primitive - scroll any rect into view
13
//! - `scroll_node_into_view`: Scroll a DOM node's bounding rect into view
14
//! - `scroll_cursor_into_view`: Scroll a text cursor position into view
15
//!
16
//! # W3C Compliance
17
//!
18
//! This implementation follows the W3C CSSOM View Module specification:
19
//! - `ScrollLogicalPosition`: start, center, end, nearest
20
//! - `ScrollBehavior`: auto, instant, smooth
21
//! - Proper scroll ancestor chain traversal
22

            
23
use alloc::vec::Vec;
24

            
25
// Re-export types from core for public API
26
pub use azul_core::events::{ScrollIntoViewBehavior, ScrollIntoViewOptions, ScrollLogicalPosition};
27
use azul_core::{
28
    dom::{DomId, DomNodeId, NodeId},
29
    geom::{LogicalPosition, LogicalRect, LogicalSize},
30
    task::{Duration, Instant},
31
};
32

            
33
use crate::{
34
    managers::scroll_state::ScrollManager,
35
    solver3::{
36
        getters::{get_overflow_x, get_overflow_y},
37
        layout_tree::LayoutNodeId,
38
    },
39
    window::DomLayoutResult,
40
};
41

            
42
/// Minimum scroll delta (in logical pixels) below which scrolling is skipped
43
const SCROLL_DELTA_THRESHOLD: f32 = 0.5;
44
/// Duration of smooth scroll animations in milliseconds
45
const SMOOTH_SCROLL_DURATION_MS: u64 = 300;
46

            
47
/// Calculated scroll adjustment for one scroll container
48
#[derive(Copy, Debug, Clone)]
49
pub struct ScrollAdjustment {
50
    /// The DOM containing the scroll container
51
    pub scroll_container_dom_id: DomId,
52
    /// The node ID of the scroll container within the DOM
53
    pub scroll_container_node_id: NodeId,
54
    /// The scroll delta to apply
55
    pub delta: LogicalPosition,
56
    /// The scroll behavior to use
57
    pub behavior: ScrollIntoViewBehavior,
58
}
59

            
60
/// Information about a scrollable ancestor
61
#[derive(Debug, Clone)]
62
struct ScrollableAncestor {
63
    dom_id: DomId,
64
    node_id: NodeId,
65
    /// What to ADD to the target rect to express it in this ancestor's dom.
66
    ///
67
    /// Zero within one dom, where everything already shares an absolute space.
68
    /// Non-zero once the walk has crossed out of a `VirtualView`'s nested dom,
69
    /// whose display list is 0-relative and composited at
70
    /// `host.origin + content_offset`.
71
    target_lift: LogicalPosition,
72
    /// The visible rect of the scroll container (content area)
73
    visible_rect: LogicalRect,
74
    /// Whether horizontal scroll is enabled
75
    scroll_x: bool,
76
    /// Whether vertical scroll is enabled
77
    scroll_y: bool,
78
}
79

            
80
/// Resolve a nested dom to the `VirtualView` that hosts it:
81
/// `(host's dom, host node, offset that converts nested geometry to the host's
82
/// space)`.
83
///
84
/// Passed in rather than reaching for `VirtualViewManager` so this module stays
85
/// independent of it — and so a test can hand in a fixture chain.
86
pub type NestedDomHop<'a> = &'a dyn Fn(DomId) -> Option<(DomId, NodeId, LogicalPosition)>;
87

            
88
// ============================================================================
89
// Core API: scroll_rect_into_view
90
// ============================================================================
91

            
92
/// Core function: scroll a rect into the visible area of its scroll containers
93
///
94
/// This is the ONLY scroll-into-view primitive. All higher-level APIs call this.
95
///
96
/// # Arguments
97
///
98
/// * `target_rect` - The rectangle to make visible (in absolute coordinates)
99
/// * `target_dom_id` - The DOM containing the target node
100
/// * `target_node_id` - The target node (used for finding scroll ancestors)
101
/// * `layout_results` - Layout data for all DOMs
102
/// * `scroll_manager` - Current scroll state
103
/// * `options` - How to scroll (alignment and animation)
104
/// * `now` - Current timestamp for animation
105
///
106
/// # Returns
107
///
108
/// A vector of scroll adjustments for each scroll container in the ancestry chain.
109
/// The adjustments are ordered from innermost (closest to target) to outermost.
110
// Instant is a ref-counted FFI clock handle threaded through the event loop by value;
111
// &-converting would cascade through the loop call chain.
112
#[allow(clippy::needless_pass_by_value)]
113
89
pub(crate) fn scroll_rect_into_view(
114
89
    target_rect: LogicalRect,
115
89
    target_dom_id: DomId,
116
89
    target_node_id: NodeId,
117
89
    layout_results: &alloc::collections::BTreeMap<DomId, DomLayoutResult>,
118
89
    scroll_manager: &mut ScrollManager,
119
89
    options: ScrollIntoViewOptions,
120
89
    now: Instant,
121
89
    hop: NestedDomHop<'_>,
122
89
) -> Vec<ScrollAdjustment> {
123
89
    let mut adjustments = Vec::new();
124

            
125
    // Find scrollable ancestors from target to root
126
89
    let scroll_ancestors = find_scrollable_ancestors(
127
89
        target_dom_id,
128
89
        target_node_id,
129
89
        layout_results,
130
89
        scroll_manager,
131
89
        hop,
132
    );
133

            
134
89
    if scroll_ancestors.is_empty() {
135
47
        return adjustments;
136
42
    }
137

            
138
    // Transform target_rect relative to each scroll container and calculate deltas
139
42
    let mut current_rect = target_rect;
140

            
141
95
    for ancestor in scroll_ancestors {
142
        // Express the target in THIS ancestor's dom before comparing. Zero
143
        // within one dom; non-zero once the walk has left a nested one.
144
53
        let mut compare_rect = current_rect;
145
53
        compare_rect.origin.x += ancestor.target_lift.x;
146
53
        compare_rect.origin.y += ancestor.target_lift.y;
147

            
148
        // Calculate the scroll delta based on options
149
53
        let delta = calculate_scroll_delta(
150
53
            compare_rect,
151
53
            ancestor.visible_rect,
152
53
            options.block,
153
53
            options.inline_axis,
154
53
            ancestor.scroll_x,
155
53
            ancestor.scroll_y,
156
        );
157

            
158
        // Only add adjustment if there's actual scrolling to do
159
53
        if delta.x.abs() > SCROLL_DELTA_THRESHOLD || delta.y.abs() > SCROLL_DELTA_THRESHOLD {
160
36
            // Resolve scroll behavior
161
36
            let behavior = resolve_scroll_behavior(
162
36
                options.behavior,
163
36
                ancestor.dom_id,
164
36
                ancestor.node_id,
165
36
                layout_results,
166
36
            );
167
36

            
168
36
            // Apply the scroll adjustment
169
36
            apply_scroll_adjustment(
170
36
                scroll_manager,
171
36
                ancestor.dom_id,
172
36
                ancestor.node_id,
173
36
                delta,
174
36
                behavior,
175
36
                now.clone(),
176
36
            );
177
36

            
178
36
            adjustments.push(ScrollAdjustment {
179
36
                scroll_container_dom_id: ancestor.dom_id,
180
36
                scroll_container_node_id: ancestor.node_id,
181
36
                delta,
182
36
                behavior,
183
36
            });
184
36

            
185
36
            // Adjust current_rect for next iteration (relative to new scroll position)
186
36
            current_rect.origin.x -= delta.x;
187
36
            current_rect.origin.y -= delta.y;
188
36
        }
189
    }
190

            
191
42
    adjustments
192
89
}
193

            
194
// ============================================================================
195
// Higher-Level APIs
196
// ============================================================================
197

            
198
/// Scroll a DOM node's bounding rect into view
199
///
200
/// This is a convenience wrapper around `scroll_rect_into_view` that
201
/// automatically gets the node's bounding rect from layout results.
202
75
pub fn scroll_node_into_view(
203
75
    node_id: DomNodeId,
204
75
    layout_results: &alloc::collections::BTreeMap<DomId, DomLayoutResult>,
205
75
    scroll_manager: &mut ScrollManager,
206
75
    options: ScrollIntoViewOptions,
207
75
    now: Instant,
208
75
    hop: NestedDomHop<'_>,
209
75
) -> Vec<ScrollAdjustment> {
210
    // Get node's bounding rect from layout
211
75
    let Some(target_rect) = get_node_rect(node_id, layout_results) else {
212
4
        return Vec::new();
213
    };
214

            
215
71
    let Some(internal_node_id) = node_id.node.into_crate_internal() else {
216
        return Vec::new();
217
    };
218

            
219
    // Call the core rect-based API
220
71
    scroll_rect_into_view(
221
71
        target_rect,
222
71
        node_id.dom,
223
71
        internal_node_id,
224
71
        layout_results,
225
71
        scroll_manager,
226
71
        options,
227
71
        now,
228
71
        hop,
229
    )
230
75
}
231

            
232
/// Scroll a text cursor position into view
233
///
234
/// Transforms the cursor's visual rect (in node-local coordinates) to absolute
235
/// coordinates before scrolling.
236
8
pub fn scroll_cursor_into_view(
237
8
    cursor_rect: LogicalRect,
238
8
    node_id: DomNodeId,
239
8
    layout_results: &alloc::collections::BTreeMap<DomId, DomLayoutResult>,
240
8
    scroll_manager: &mut ScrollManager,
241
8
    options: ScrollIntoViewOptions,
242
8
    now: Instant,
243
8
    hop: NestedDomHop<'_>,
244
8
) -> Vec<ScrollAdjustment> {
245
    // Get node's position to transform cursor_rect to absolute coordinates
246
8
    let Some(node_rect) = get_node_rect(node_id, layout_results) else {
247
2
        return Vec::new();
248
    };
249

            
250
    // Transform cursor rect to absolute coordinates
251
6
    let absolute_cursor_rect = LogicalRect {
252
6
        origin: LogicalPosition {
253
6
            x: node_rect.origin.x + cursor_rect.origin.x,
254
6
            y: node_rect.origin.y + cursor_rect.origin.y,
255
6
        },
256
6
        size: cursor_rect.size,
257
6
    };
258

            
259
6
    let Some(internal_node_id) = node_id.node.into_crate_internal() else {
260
        return Vec::new();
261
    };
262

            
263
    // Call the core rect-based API
264
6
    scroll_rect_into_view(
265
6
        absolute_cursor_rect,
266
6
        node_id.dom,
267
6
        internal_node_id,
268
6
        layout_results,
269
6
        scroll_manager,
270
6
        options,
271
6
        now,
272
6
        hop,
273
    )
274
8
}
275

            
276
// ============================================================================
277
// Helper Functions
278
// ============================================================================
279

            
280
/// Find all scrollable ancestors from a node to the root
281
///
282
/// Returns ancestors ordered from innermost (closest to target) to outermost (root).
283
96
fn find_scrollable_ancestors(
284
96
    dom_id: DomId,
285
96
    node_id: NodeId,
286
96
    layout_results: &alloc::collections::BTreeMap<DomId, DomLayoutResult>,
287
96
    scroll_manager: &ScrollManager,
288
96
    hop: NestedDomHop<'_>,
289
96
) -> Vec<ScrollableAncestor> {
290
96
    let mut ancestors = Vec::new();
291
96
    let mut current_dom = dom_id;
292
96
    let mut current = Some(node_id);
293
    // What to add to the target rect to express it in `current_dom`.
294
96
    let mut lift = LogicalPosition::zero();
295
96
    let mut crossings = 0usize;
296
96
    let mut entered_by_crossing = false;
297

            
298
    'walk: loop {
299
97
        let Some(layout_result) = layout_results.get(&current_dom) else {
300
2
            return ancestors;
301
        };
302
95
        let node_hierarchy = layout_result.styled_dom.node_hierarchy.as_container();
303

            
304
        // In the target's OWN dom start above it: scrolling a container into
305
        // its own scrollport is not a thing. After a crossing, start AT the
306
        // host — the VirtualView clips the nested content, so it is a genuine
307
        // scroll ancestor of everything inside it.
308
95
        let mut node = if entered_by_crossing {
309
1
            current
310
        } else {
311
94
            current
312
94
                .and_then(|n| node_hierarchy.get(n))
313
94
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
314
        };
315

            
316
333
        while let Some(current_node_id) = node {
317
57
            if let Some(mut ancestor) =
318
238
                check_if_scrollable(current_dom, current_node_id, layout_result, scroll_manager)
319
57
            {
320
57
                ancestor.target_lift = lift;
321
57
                ancestors.push(ancestor);
322
181
            }
323
238
            node = node_hierarchy
324
238
                .get(current_node_id)
325
238
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id);
326
        }
327

            
328
        // Reached this dom's root. A nested dom is a WINDOW inside a
329
        // VirtualView, so its scroll ancestry continues in the host's dom —
330
        // stopping here meant a caret inside a virtualized view could never be
331
        // revealed through the containers that actually clip it.
332
95
        crossings += 1;
333
95
        if crossings > NESTED_DOM_CROSSING_LIMIT {
334
            break 'walk;
335
95
        }
336
95
        match hop(current_dom) {
337
1
            Some((parent_dom, host_node, offset)) => {
338
1
                lift.x += offset.x;
339
1
                lift.y += offset.y;
340
1
                current_dom = parent_dom;
341
1
                current = Some(host_node);
342
1
                entered_by_crossing = true;
343
1
            }
344
94
            None => break 'walk,
345
        }
346
    }
347

            
348
94
    ancestors
349
96
}
350

            
351
/// How many `VirtualView` boundaries [`find_scrollable_ancestors`] will cross.
352
/// Nesting is shallow; the bound only stops a cycle.
353
const NESTED_DOM_CROSSING_LIMIT: usize = 32;
354

            
355
/// Check if a node is scrollable and return its scroll info
356
247
fn check_if_scrollable(
357
247
    dom_id: DomId,
358
247
    node_id: NodeId,
359
247
    layout_result: &DomLayoutResult,
360
247
    scroll_manager: &ScrollManager,
361
247
) -> Option<ScrollableAncestor> {
362
247
    let styled_nodes = layout_result.styled_dom.styled_nodes.as_container();
363
247
    let styled_node = styled_nodes.get(node_id)?;
364

            
365
246
    let overflow_x = get_overflow_x(
366
246
        &layout_result.styled_dom,
367
246
        node_id,
368
246
        &styled_node.styled_node_state,
369
    );
370
246
    let overflow_y = get_overflow_y(
371
246
        &layout_result.styled_dom,
372
246
        node_id,
373
246
        &styled_node.styled_node_state,
374
    );
375

            
376
    // Programmatic scrolling reaches EVERY scroll container - including
377
    // overflow:hidden, whose user scrolling is disabled but which css
378
    // overflow-3 §3.1 keeps programmatically scrollable (scrollIntoView
379
    // through a hidden clipper is the canonical carousel/tab-panel case).
380
246
    let scroll_x = overflow_x.is_scroll_container();
381
246
    let scroll_y = overflow_y.is_scroll_container();
382

            
383
    // If neither axis is scrollable, skip this node
384
246
    if !scroll_x && !scroll_y {
385
156
        return None;
386
90
    }
387

            
388
    // Check if the scroll manager has scroll state for this node
389
    // (which means it actually has overflowing content)
390
90
    let scroll_state = scroll_manager.get_scroll_state(dom_id, node_id)?;
391

            
392
    // Check if content actually overflows (use virtual_scroll_size when set, e.g. for VirtualView)
393
63
    let effective_width = scroll_state
394
63
        .virtual_scroll_size
395
63
        .map_or(scroll_state.content_rect.size.width, |s| s.width);
396
63
    let effective_height = scroll_state
397
63
        .virtual_scroll_size
398
63
        .map_or(scroll_state.content_rect.size.height, |s| s.height);
399
63
    let has_overflow_x = effective_width > scroll_state.container_rect.size.width;
400
63
    let has_overflow_y = effective_height > scroll_state.container_rect.size.height;
401

            
402
63
    if !has_overflow_x && !has_overflow_y {
403
2
        return None;
404
61
    }
405

            
406
    // The visible rect = the SCROLLPORT (padding box, static layout coords —
407
    // see `managers::scroll_registration`) shifted by the current scroll
408
    // offset. Origin and size both come off the one box the manager published,
409
    // so this cannot drift from what the caret reveal and the auto-scroll
410
    // timer measure against.
411
61
    let visible_rect = LogicalRect {
412
61
        origin: LogicalPosition {
413
61
            x: scroll_state.container_rect.origin.x + scroll_state.current_offset.x,
414
61
            y: scroll_state.container_rect.origin.y + scroll_state.current_offset.y,
415
61
        },
416
61
        size: scroll_state.container_rect.size,
417
61
    };
418

            
419
    Some(ScrollableAncestor {
420
61
        dom_id,
421
61
        node_id,
422
        // Filled in by the walk, which is what knows how many VirtualView
423
        // boundaries were crossed to reach this ancestor.
424
61
        target_lift: LogicalPosition::zero(),
425
61
        visible_rect,
426
61
        scroll_x: scroll_x && has_overflow_x,
427
61
        scroll_y: scroll_y && has_overflow_y,
428
    })
429
247
}
430

            
431
/// Calculate the scroll delta needed to bring target into view within container
432
#[allow(clippy::similar_names)] // domain-standard coordinate/geometry/short-lived names
433
58
fn calculate_scroll_delta(
434
58
    target: LogicalRect,
435
58
    container: LogicalRect,
436
58
    block: ScrollLogicalPosition,
437
58
    inline: ScrollLogicalPosition,
438
58
    scroll_x_enabled: bool,
439
58
    scroll_y_enabled: bool,
440
58
) -> LogicalPosition {
441
    LogicalPosition {
442
58
        x: if scroll_x_enabled {
443
5
            calculate_axis_delta(
444
5
                target.origin.x,
445
5
                target.size.width,
446
5
                container.origin.x,
447
5
                container.size.width,
448
5
                inline,
449
            )
450
        } else {
451
53
            0.0
452
        },
453
58
        y: if scroll_y_enabled {
454
56
            calculate_axis_delta(
455
56
                target.origin.y,
456
56
                target.size.height,
457
56
                container.origin.y,
458
56
                container.size.height,
459
56
                block,
460
            )
461
        } else {
462
2
            0.0
463
        },
464
    }
465
58
}
466

            
467
/// Calculate scroll delta for a single axis
468
#[must_use]
469
196
pub fn calculate_axis_delta(
470
196
    target_start: f32,
471
196
    target_size: f32,
472
196
    container_start: f32,
473
196
    container_size: f32,
474
196
    position: ScrollLogicalPosition,
475
196
) -> f32 {
476
196
    let target_end = target_start + target_size;
477
196
    let container_end = container_start + container_size;
478

            
479
196
    match position {
480
        ScrollLogicalPosition::Start => {
481
            // Align target start with container start
482
41
            target_start - container_start
483
        }
484
        ScrollLogicalPosition::End => {
485
            // Align target end with container end
486
19
            target_end - container_end
487
        }
488
        ScrollLogicalPosition::Center => {
489
            // Center target in container
490
18
            let target_center = target_start + target_size / 2.0;
491
18
            let container_center = container_start + container_size / 2.0;
492
18
            target_center - container_center
493
        }
494
        ScrollLogicalPosition::Nearest => {
495
            // A target BIGGER than the scrollport that is already on screen is
496
            // already "in view" — there is no scroll position that shows all
497
            // of it, and every candidate is equally (in)complete. Scrolling
498
            // anyway yanks the page under the user: focusing AzWriter's
499
            // contenteditable (929px tall in a 357px viewport, starting 113px
500
            // down the page) fell through to "align the target's start" and
501
            // scrolled the page's whole TOP MARGIN off screen, leaving the
502
            // caret jammed against the top edge on a freshly opened document.
503
            //
504
            // "Nearest" means the MINIMUM scroll that satisfies the request,
505
            // and when the request is already satisfied that minimum is zero.
506
            // Only an oversized target that is entirely off screen still gets
507
            // pulled in by the arms below.
508
118
            let intersects = target_end > container_start && target_start < container_end;
509
118
            if target_size > container_size && intersects {
510
15
                return 0.0;
511
103
            }
512
            // Minimum scroll to make target fully visible
513
103
            if target_start < container_start {
514
                // Target is above/left of visible area - scroll up/left
515
27
                target_start - container_start
516
76
            } else if target_end > container_end {
517
                // Target is below/right of visible area
518
47
                if target_size <= container_size {
519
                    // Target fits, align end with container end
520
41
                    target_end - container_end
521
                } else {
522
                    // Target doesn't fit, align start with container start
523
6
                    target_start - container_start
524
                }
525
            } else {
526
                // Target is already fully visible
527
29
                0.0
528
            }
529
        }
530
    }
531
196
}
532

            
533
/// Resolve scroll behavior based on options and CSS properties
534
// +spec:containing-block:03528c - scroll-behavior on root element applies to viewport
535
45
const fn resolve_scroll_behavior(
536
45
    requested: ScrollIntoViewBehavior,
537
45
    _dom_id: DomId,
538
45
    _node_id: NodeId,
539
45
    _layout_results: &alloc::collections::BTreeMap<DomId, DomLayoutResult>,
540
45
) -> ScrollIntoViewBehavior {
541
45
    match requested {
542
        ScrollIntoViewBehavior::Auto => {
543
            // TODO: Check CSS scroll-behavior property on the scroll container
544
            // For now, default to instant
545
24
            ScrollIntoViewBehavior::Instant
546
        }
547
21
        other => other,
548
    }
549
45
}
550

            
551
/// Apply a scroll adjustment to the scroll manager
552
48
fn apply_scroll_adjustment(
553
48
    scroll_manager: &mut ScrollManager,
554
48
    dom_id: DomId,
555
48
    node_id: NodeId,
556
48
    delta: LogicalPosition,
557
48
    behavior: ScrollIntoViewBehavior,
558
48
    now: Instant,
559
48
) {
560
    use azul_core::{events::EasingFunction, task::SystemTimeDiff};
561

            
562
48
    let current = scroll_manager
563
48
        .get_current_offset(dom_id, node_id)
564
48
        .unwrap_or_default();
565

            
566
48
    let new_position = LogicalPosition {
567
48
        x: current.x + delta.x,
568
48
        y: current.y + delta.y,
569
48
    };
570

            
571
48
    match behavior {
572
46
        ScrollIntoViewBehavior::Instant | ScrollIntoViewBehavior::Auto => {
573
46
            scroll_manager.set_scroll_position(dom_id, node_id, new_position, now);
574
46
        }
575
2
        ScrollIntoViewBehavior::Smooth => {
576
2
            // Use smooth scroll with 300ms duration
577
2
            let duration = Duration::System(SystemTimeDiff::from_millis(SMOOTH_SCROLL_DURATION_MS));
578
2
            scroll_manager.scroll_to(
579
2
                dom_id,
580
2
                node_id,
581
2
                new_position,
582
2
                duration,
583
2
                EasingFunction::EaseOut,
584
2
                now,
585
2
            );
586
2
        }
587
    }
588
48
}
589

            
590
/// Get a node's bounding rect from layout results
591
92
fn get_node_rect(
592
92
    node_id: DomNodeId,
593
92
    layout_results: &alloc::collections::BTreeMap<DomId, DomLayoutResult>,
594
92
) -> Option<LogicalRect> {
595
92
    let layout_result = layout_results.get(&node_id.dom)?;
596
87
    let nid = node_id.node.into_crate_internal()?;
597

            
598
    // Get position
599
84
    let layout_indices = layout_result.layout_tree.dom_to_layout.get(&nid)?;
600
81
    let layout_index = *layout_indices.first()?;
601
80
    let position = *layout_result
602
80
        .calculated_positions
603
80
        .get(layout_index.index())?;
604

            
605
    // Get size
606
79
    let layout_node = layout_result.layout_tree.get(layout_index)?;
607
79
    let size = layout_node.used_size?;
608

            
609
78
    Some(LogicalRect::new(position, size))
610
92
}
611

            
612
#[cfg(test)]
613
mod autotest_generated {
614
    /// The fixtures here are single-dom: there is no `VirtualView` boundary to
615
    /// cross, so the walk stops at the root exactly as it always did.
616
    fn no_hop(_: DomId) -> Option<(DomId, NodeId, LogicalPosition)> {
617
        None
618
    }
619

            
620
    use alloc::collections::BTreeMap;
621
    use std::collections::HashMap;
622

            
623
    use azul_core::{
624
        dom::{Dom, FormattingContext, IdOrClass},
625
        styled_dom::{NodeHierarchyItemId, StyledDom},
626
    };
627

            
628
    use super::*;
629
    use crate::solver3::{
630
        display_list::DisplayList,
631
        geometry::PackedBoxProps,
632
        layout_tree::{LayoutNodeHot, LayoutTree},
633
    };
634

            
635
    // ------------------------------------------------------------------
636
    // Fixtures
637
    // ------------------------------------------------------------------
638

            
639
    /// Flat node indices of [`chain_dom`]. The fixture is a *linear* chain, so
640
    /// these indices hold under any tree-flattening order.
641
    const OUTER: usize = 1;
642
    const INNER: usize = 2;
643
    const TARGET: usize = 3;
644
    /// A node index far past the end of the fixture DOM.
645
    const OUT_OF_RANGE: usize = 9999;
646

            
647
    const SCROLL_CSS: &str = ".outer { overflow-x: scroll; overflow-y: scroll; } .inner { \
648
                              overflow-x: scroll; overflow-y: scroll; }";
649
    const X_ONLY_CSS: &str = ".inner { overflow-x: scroll; }";
650
    const NO_CSS: &str = "";
651

            
652
    fn dom_id(inner: usize) -> DomId {
653
        DomId { inner }
654
    }
655

            
656
    fn nid(index: usize) -> NodeId {
657
        NodeId::new(index)
658
    }
659

            
660
    fn dnid(dom: usize, index: usize) -> DomNodeId {
661
        DomNodeId {
662
            dom: dom_id(dom),
663
            node: NodeHierarchyItemId::from_crate_internal(Some(nid(index))),
664
        }
665
    }
666

            
667
    /// A `DomNodeId` whose node slot is the "no node" sentinel.
668
    fn null_dnid(dom: usize) -> DomNodeId {
669
        DomNodeId {
670
            dom: dom_id(dom),
671
            node: NodeHierarchyItemId::NONE,
672
        }
673
    }
674

            
675
    fn pos(x: f32, y: f32) -> LogicalPosition {
676
        LogicalPosition::new(x, y)
677
    }
678

            
679
    fn size(width: f32, height: f32) -> LogicalSize {
680
        LogicalSize::new(width, height)
681
    }
682

            
683
    fn rect(x: f32, y: f32, width: f32, height: f32) -> LogicalRect {
684
        LogicalRect::new(pos(x, y), size(width, height))
685
    }
686

            
687
    fn close(a: f32, b: f32) -> bool {
688
        (a - b).abs() < 1e-3
689
    }
690

            
691
    fn now() -> Instant {
692
        Instant::now()
693
    }
694

            
695
    fn opts(
696
        block: ScrollLogicalPosition,
697
        inline_axis: ScrollLogicalPosition,
698
        behavior: ScrollIntoViewBehavior,
699
    ) -> ScrollIntoViewOptions {
700
        ScrollIntoViewOptions {
701
            block,
702
            inline_axis,
703
            behavior,
704
        }
705
    }
706

            
707
    fn div_with_class(class: &str) -> Dom {
708
        Dom::create_div().with_ids_and_classes(vec![IdOrClass::Class(class.into())].into())
709
    }
710

            
711
    /// `body(0) > .outer(1) > .inner(2) > .target(3)` — a strictly linear chain,
712
    /// styled through a real class stylesheet (not `Dom::with_css`, whose scoped
713
    /// `*` rule would also match the descendants and blur which node is styled).
714
    fn chain_dom(css_str: &str) -> StyledDom {
715
        let mut dom = Dom::create_body().with_child(
716
            div_with_class("outer")
717
                .with_child(div_with_class("inner").with_child(div_with_class("target"))),
718
        );
719
        let (css, _warnings) = azul_css::parser2::new_from_str(css_str);
720
        StyledDom::create(&mut dom, css)
721
    }
722

            
723
    fn empty_layout_tree() -> LayoutTree {
724
        LayoutTree {
725
            nodes: Vec::new(),
726
            warm: Vec::new(),
727
            cold: Vec::new(),
728
            root: 0,
729
            dom_to_layout: BTreeMap::new(),
730
            children_arena: Vec::new(),
731
            children_offsets: Vec::new(),
732
            subtree_needs_intrinsic: Vec::new(),
733
        }
734
    }
735

            
736
    /// A `DomLayoutResult` with an *empty* layout tree. Everything except
737
    /// `get_node_rect` reads only `styled_dom`, so no real layout is needed.
738
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
739
        DomLayoutResult {
740
            styled_dom,
741
            layout_tree: empty_layout_tree(),
742
            calculated_positions: Vec::new(),
743
            viewport: LogicalRect::zero(),
744
            display_list: std::sync::Arc::new(DisplayList::default()),
745
            scroll_ids: HashMap::new(),
746
            scroll_id_to_node_id: HashMap::new(),
747
        }
748
    }
749

            
750
    /// One layout box per entry, in order: DOM node `n` maps to layout index `i`,
751
    /// laid out at `p` with used size `s`.
752
    fn layout_result_with_boxes(
753
        styled_dom: StyledDom,
754
        boxes: &[(usize, LogicalPosition, Option<LogicalSize>)],
755
    ) -> DomLayoutResult {
756
        let mut lr = layout_result(styled_dom);
757
        for (layout_index, (node_index, position, used_size)) in boxes.iter().enumerate() {
758
            lr.layout_tree
759
                .dom_to_layout
760
                .insert(nid(*node_index), vec![LayoutNodeId::new(layout_index)]);
761
            lr.layout_tree.nodes.push(LayoutNodeHot {
762
                box_props: PackedBoxProps::default(),
763
                dom_node_id: Some(nid(*node_index)),
764
                used_size: *used_size,
765
                formatting_context: FormattingContext::Block {
766
                    establishes_new_context: false,
767
                },
768
                parent: None,
769
            });
770
            lr.calculated_positions.push(*position);
771
        }
772
        lr
773
    }
774

            
775
    fn window(lr: DomLayoutResult) -> BTreeMap<DomId, DomLayoutResult> {
776
        let mut map = BTreeMap::new();
777
        map.insert(dom_id(0), lr);
778
        map
779
    }
780

            
781
    fn register(sm: &mut ScrollManager, node: usize, container: LogicalRect, content: LogicalSize) {
782
        sm.register_or_update_scroll_node(
783
            dom_id(0),
784
            nid(node),
785
            container,
786
            content,
787
            now(),
788
            16.0,
789
            8.0,
790
            false,
791
            false,
792
        );
793
    }
794

            
795
    /// `.inner` (node 2) is a 100×100 scroll container at the origin holding
796
    /// 100×1000 of content: vertical overflow only, max scroll y = 900.
797
    /// `.outer` (node 1) is styled scrollable but never registered with the scroll
798
    /// manager, so it is *not* a live scroll container.
799
    fn inner_only() -> (BTreeMap<DomId, DomLayoutResult>, ScrollManager) {
800
        let layout_results = window(layout_result(chain_dom(SCROLL_CSS)));
801
        let mut sm = ScrollManager::new();
802
        register(
803
            &mut sm,
804
            INNER,
805
            rect(0.0, 0.0, 100.0, 100.0),
806
            size(100.0, 1000.0),
807
        );
808
        (layout_results, sm)
809
    }
810

            
811
    // ==================================================================
812
    // calculate_axis_delta — numeric: zero / min_max / negative / nan_inf
813
    // ==================================================================
814

            
815
    #[test]
816
    fn axis_delta_all_zero_inputs_are_zero_for_every_position() {
817
        for position in [
818
            ScrollLogicalPosition::Start,
819
            ScrollLogicalPosition::Center,
820
            ScrollLogicalPosition::End,
821
            ScrollLogicalPosition::Nearest,
822
        ] {
823
            let delta = calculate_axis_delta(0.0, 0.0, 0.0, 0.0, position);
824
            assert!(close(delta, 0.0), "{position:?} on all-zero input");
825
        }
826
    }
827

            
828
    #[test]
829
    fn axis_delta_start_aligns_target_start_with_container_start() {
830
        assert!(close(
831
            calculate_axis_delta(100.0, 50.0, 20.0, 30.0, ScrollLogicalPosition::Start),
832
            80.0
833
        ));
834
    }
835

            
836
    #[test]
837
    fn axis_delta_end_aligns_target_end_with_container_end() {
838
        // target 100..150, container 0..30 => 150 - 30
839
        assert!(close(
840
            calculate_axis_delta(100.0, 50.0, 0.0, 30.0, ScrollLogicalPosition::End),
841
            120.0
842
        ));
843
    }
844

            
845
    #[test]
846
    fn axis_delta_center_aligns_midpoints() {
847
        // target center 120, container center 50
848
        assert!(close(
849
            calculate_axis_delta(100.0, 40.0, 0.0, 100.0, ScrollLogicalPosition::Center),
850
            70.0
851
        ));
852
    }
853

            
854
    #[test]
855
    fn axis_delta_center_of_zero_sized_target_is_offset_of_container_center() {
856
        assert!(close(
857
            calculate_axis_delta(0.0, 0.0, 0.0, 100.0, ScrollLogicalPosition::Center),
858
            -50.0
859
        ));
860
    }
861

            
862
    #[test]
863
    fn axis_delta_nearest_leaves_fully_visible_target_alone() {
864
        // target 10..30 inside container 0..100
865
        assert!(close(
866
            calculate_axis_delta(10.0, 20.0, 0.0, 100.0, ScrollLogicalPosition::Nearest),
867
            0.0
868
        ));
869
    }
870

            
871
    #[test]
872
    fn axis_delta_nearest_scrolls_back_for_target_before_container() {
873
        assert!(close(
874
            calculate_axis_delta(-40.0, 20.0, 0.0, 100.0, ScrollLogicalPosition::Nearest),
875
            -40.0
876
        ));
877
    }
878

            
879
    #[test]
880
    fn axis_delta_nearest_aligns_end_when_target_fits() {
881
        // target 150..170 (size 20) below container 0..100 => end-align
882
        assert!(close(
883
            calculate_axis_delta(150.0, 20.0, 0.0, 100.0, ScrollLogicalPosition::Nearest),
884
            70.0
885
        ));
886
    }
887

            
888
    #[test]
889
    fn axis_delta_nearest_aligns_start_when_target_does_not_fit() {
890
        // target 150..450 (size 300) is bigger than the 100px container => start-align
891
        assert!(close(
892
            calculate_axis_delta(150.0, 300.0, 0.0, 100.0, ScrollLogicalPosition::Nearest),
893
            150.0
894
        ));
895
    }
896

            
897
    #[test]
898
    fn axis_delta_handles_negative_coordinates_deterministically() {
899
        // container -100..-50, target -200..-190
900
        assert!(close(
901
            calculate_axis_delta(-200.0, 10.0, -100.0, 50.0, ScrollLogicalPosition::Start),
902
            -100.0
903
        ));
904
        assert!(close(
905
            calculate_axis_delta(-200.0, 10.0, -100.0, 50.0, ScrollLogicalPosition::End),
906
            -140.0
907
        ));
908
        assert!(close(
909
            calculate_axis_delta(-200.0, 10.0, -100.0, 50.0, ScrollLogicalPosition::Nearest),
910
            -100.0
911
        ));
912
    }
913

            
914
    #[test]
915
    fn axis_delta_nearest_never_scrolls_the_wrong_way() {
916
        let (container_start, container_size) = (100.0f32, 50.0f32);
917
        for target_start in [-1000.0f32, 0.0, 99.0, 100.0, 120.0, 149.0, 150.0, 1000.0] {
918
            for target_size in [0.0f32, 10.0, 50.0, 60.0] {
919
                let delta = calculate_axis_delta(
920
                    target_start,
921
                    target_size,
922
                    container_start,
923
                    container_size,
924
                    ScrollLogicalPosition::Nearest,
925
                );
926
                let start_align = target_start - container_start;
927
                let end_align = (target_start + target_size) - (container_start + container_size);
928
                let fully_visible = target_start >= container_start
929
                    && (target_start + target_size) <= (container_start + container_size);
930

            
931
                // The delta is always one of {0, start-align, end-align} — never an
932
                // arbitrary value, and never an overshoot past both alignments.
933
                assert!(
934
                    close(delta, 0.0) || close(delta, start_align) || close(delta, end_align),
935
                    "delta {delta} for target {target_start}+{target_size}"
936
                );
937
                if fully_visible {
938
                    assert!(
939
                        close(delta, 0.0),
940
                        "visible target {target_start}+{target_size} must not scroll"
941
                    );
942
                }
943
                if target_start < container_start {
944
                    // Target starts before the viewport: only ever scroll backwards.
945
                    assert!(delta <= 0.0, "delta {delta} scrolled the wrong way");
946
                }
947
            }
948
        }
949
    }
950

            
951
    #[test]
952
    fn axis_delta_nan_target_start_does_not_panic() {
953
        // Start/End/Center are pure arithmetic: NaN propagates (a defined f32 result).
954
        for position in [
955
            ScrollLogicalPosition::Start,
956
            ScrollLogicalPosition::End,
957
            ScrollLogicalPosition::Center,
958
        ] {
959
            let delta = calculate_axis_delta(f32::NAN, 10.0, 0.0, 100.0, position);
960
            assert!(
961
                delta.is_nan(),
962
                "{position:?} should propagate NaN, got {delta}"
963
            );
964
        }
965
    }
966

            
967
    #[test]
968
    fn axis_delta_nan_target_start_is_zero_for_nearest() {
969
        // Every NaN comparison is false, so `Nearest` falls through to the
970
        // "already fully visible" branch and returns exactly 0.0 — the safe
971
        // choice (no scroll) rather than a NaN leaking into the scroll offset.
972
        let delta =
973
            calculate_axis_delta(f32::NAN, 10.0, 0.0, 100.0, ScrollLogicalPosition::Nearest);
974
        assert_eq!(delta, 0.0);
975
    }
976

            
977
    #[test]
978
    fn axis_delta_nan_container_does_not_panic() {
979
        for position in [
980
            ScrollLogicalPosition::Start,
981
            ScrollLogicalPosition::End,
982
            ScrollLogicalPosition::Center,
983
            ScrollLogicalPosition::Nearest,
984
        ] {
985
            let delta = calculate_axis_delta(0.0, 10.0, f32::NAN, f32::NAN, position);
986
            assert!(
987
                delta.is_nan() || delta == 0.0,
988
                "{position:?} gave {delta} for a NaN container"
989
            );
990
        }
991
    }
992

            
993
    #[test]
994
    fn axis_delta_infinite_target_start_saturates_to_infinity() {
995
        let delta = calculate_axis_delta(
996
            f32::INFINITY,
997
            10.0,
998
            0.0,
999
            100.0,
            ScrollLogicalPosition::Start,
        );
        assert!(delta.is_infinite() && delta.is_sign_positive());
        let delta = calculate_axis_delta(
            f32::NEG_INFINITY,
            10.0,
            0.0,
            100.0,
            ScrollLogicalPosition::Start,
        );
        assert!(delta.is_infinite() && delta.is_sign_negative());
    }
    #[test]
    fn axis_delta_infinity_minus_infinity_is_nan_not_a_panic() {
        let delta = calculate_axis_delta(
            f32::INFINITY,
            10.0,
            f32::INFINITY,
            100.0,
            ScrollLogicalPosition::Start,
        );
        assert!(delta.is_nan());
    }
    #[test]
    fn axis_delta_infinite_sizes_do_not_panic() {
        for position in [
            ScrollLogicalPosition::Start,
            ScrollLogicalPosition::End,
            ScrollLogicalPosition::Center,
            ScrollLogicalPosition::Nearest,
        ] {
            let delta = calculate_axis_delta(0.0, f32::INFINITY, 0.0, f32::INFINITY, position);
            assert!(
                delta.is_nan() || delta.is_infinite() || delta.is_finite(),
                "{position:?} produced a non-f32 value"
            );
        }
    }
    #[test]
    fn axis_delta_f32_max_overflow_saturates_instead_of_panicking() {
        // target_start + target_size overflows f32 => +inf (IEEE saturation, no panic)
        let delta =
            calculate_axis_delta(f32::MAX, f32::MAX, 0.0, 100.0, ScrollLogicalPosition::End);
        assert!(delta.is_infinite() && delta.is_sign_positive());
        // Nearest sees target_end == +inf > container_end, and the (infinite)
        // target does not fit, so it start-aligns to a finite f32::MAX.
        let delta = calculate_axis_delta(
            f32::MAX,
            f32::MAX,
            0.0,
            100.0,
            ScrollLogicalPosition::Nearest,
        );
        assert_eq!(delta, f32::MAX);
    }
    #[test]
    fn axis_delta_f32_min_does_not_panic() {
        for position in [
            ScrollLogicalPosition::Start,
            ScrollLogicalPosition::End,
            ScrollLogicalPosition::Center,
            ScrollLogicalPosition::Nearest,
        ] {
            let delta = calculate_axis_delta(f32::MIN, 1.0, f32::MAX, 1.0, position);
            assert!(
                !delta.is_nan(),
                "{position:?} produced NaN from finite input"
            );
        }
    }
    // ==================================================================
    // calculate_scroll_delta — numeric
    // ==================================================================
    #[test]
    fn scroll_delta_zero_rects_are_zero() {
        let delta = calculate_scroll_delta(
            LogicalRect::zero(),
            LogicalRect::zero(),
            ScrollLogicalPosition::Nearest,
            ScrollLogicalPosition::Nearest,
            true,
            true,
        );
        assert_eq!((delta.x, delta.y), (0.0, 0.0));
    }
    #[test]
    fn scroll_delta_disabled_axes_are_exactly_zero_even_for_nan_and_infinite_rects() {
        let poison = LogicalRect::new(
            pos(f32::NAN, f32::INFINITY),
            size(f32::NAN, f32::NEG_INFINITY),
        );
        let delta = calculate_scroll_delta(
            poison,
            poison,
            ScrollLogicalPosition::Start,
            ScrollLogicalPosition::Start,
            false,
            false,
        );
        // Disabled axes short-circuit to 0.0 before any arithmetic runs, so no
        // NaN can reach the scroll offset.
        assert_eq!((delta.x, delta.y), (0.0, 0.0));
        assert!(delta.x.is_finite() && delta.y.is_finite());
    }
    #[test]
    fn scroll_delta_does_not_swap_the_axes() {
        // x must use `inline` + width, y must use `block` + height.
        let delta = calculate_scroll_delta(
            rect(10.0, 200.0, 5.0, 5.0),
            rect(0.0, 0.0, 100.0, 50.0),
            ScrollLogicalPosition::Start, // block  -> y
            ScrollLogicalPosition::End,   // inline -> x
            true,
            true,
        );
        assert!(
            close(delta.x, -85.0),
            "x used the wrong axis/position: {}",
            delta.x
        );
        assert!(
            close(delta.y, 200.0),
            "y used the wrong axis/position: {}",
            delta.y
        );
    }
    #[test]
    fn scroll_delta_only_enabled_axis_moves() {
        let target = rect(500.0, 500.0, 10.0, 10.0);
        let container = rect(0.0, 0.0, 100.0, 100.0);
        let x_only = calculate_scroll_delta(
            target,
            container,
            ScrollLogicalPosition::Start,
            ScrollLogicalPosition::Start,
            true,
            false,
        );
        assert!(close(x_only.x, 500.0));
        assert_eq!(x_only.y, 0.0);
        let y_only = calculate_scroll_delta(
            target,
            container,
            ScrollLogicalPosition::Start,
            ScrollLogicalPosition::Start,
            false,
            true,
        );
        assert_eq!(y_only.x, 0.0);
        assert!(close(y_only.y, 500.0));
    }
    // ==================================================================
    // resolve_scroll_behavior — predicate / invariant
    // ==================================================================
    #[test]
    fn resolve_behavior_maps_auto_to_instant_and_passes_the_rest_through() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        assert_eq!(
            resolve_scroll_behavior(ScrollIntoViewBehavior::Auto, dom_id(0), nid(TARGET), &empty),
            ScrollIntoViewBehavior::Instant
        );
        assert_eq!(
            resolve_scroll_behavior(
                ScrollIntoViewBehavior::Instant,
                dom_id(0),
                nid(TARGET),
                &empty
            ),
            ScrollIntoViewBehavior::Instant
        );
        assert_eq!(
            resolve_scroll_behavior(
                ScrollIntoViewBehavior::Smooth,
                dom_id(OUT_OF_RANGE),
                nid(OUT_OF_RANGE),
                &empty
            ),
            ScrollIntoViewBehavior::Smooth
        );
    }
    #[test]
    fn resolve_behavior_is_idempotent() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        for behavior in [
            ScrollIntoViewBehavior::Auto,
            ScrollIntoViewBehavior::Instant,
            ScrollIntoViewBehavior::Smooth,
        ] {
            let once = resolve_scroll_behavior(behavior, dom_id(0), nid(0), &empty);
            let twice = resolve_scroll_behavior(once, dom_id(0), nid(0), &empty);
            assert_eq!(
                once, twice,
                "resolving {behavior:?} twice changed the result"
            );
        }
    }
    // ==================================================================
    // apply_scroll_adjustment — numeric: zero / min_max / negative / overflow
    // ==================================================================
    /// 100×100 container, 500×500 content => max scroll (400, 400).
    fn registered_manager() -> ScrollManager {
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(500.0, 500.0),
        );
        sm
    }
    #[test]
    fn apply_zero_delta_leaves_the_offset_at_zero() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(0.0, 0.0),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn apply_on_an_unregistered_node_creates_a_zero_bounded_state() {
        // No bounds are known for the node, so max scroll is 0 and the delta is
        // clamped away entirely — it must not panic or store an unbounded offset.
        let mut sm = ScrollManager::new();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(OUT_OF_RANGE),
            pos(1234.0, 5678.0),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(OUT_OF_RANGE)).unwrap();
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn apply_instant_delta_moves_the_offset() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(50.0, 60.0),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.x, 50.0) && close(offset.y, 60.0));
        assert!(!sm.has_active_animations());
    }
    #[test]
    fn apply_negative_delta_clamps_to_zero() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(-1000.0, -1000.0),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn apply_f32_max_delta_clamps_to_max_scroll() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(f32::MAX, f32::MAX),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(
            close(offset.x, 400.0) && close(offset.y, 400.0),
            "{offset:?}"
        );
    }
    #[test]
    fn apply_infinite_delta_clamps_to_the_scroll_bounds() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(f32::INFINITY, f32::NEG_INFINITY),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        assert!(close(offset.x, 400.0) && close(offset.y, 0.0), "{offset:?}");
    }
    #[test]
    fn apply_nan_delta_cannot_poison_the_scroll_offset() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(f32::NAN, f32::NAN),
            ScrollIntoViewBehavior::Instant,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        // f32::max(NaN, 0.0) == 0.0, so the clamp scrubs the NaN.
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn apply_auto_behaves_like_instant() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(25.0, 25.0),
            ScrollIntoViewBehavior::Auto,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.x, 25.0) && close(offset.y, 25.0));
        assert!(!sm.has_active_animations());
    }
    #[test]
    fn apply_smooth_animates_instead_of_jumping() {
        let mut sm = registered_manager();
        apply_scroll_adjustment(
            &mut sm,
            dom_id(0),
            nid(INNER),
            pos(50.0, 50.0),
            ScrollIntoViewBehavior::Smooth,
            now(),
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!((offset.x, offset.y), (0.0, 0.0), "smooth must not jump");
        assert!(sm.has_active_animations(), "smooth must arm an animation");
    }
    #[test]
    fn apply_deltas_accumulate_onto_the_current_offset() {
        let mut sm = registered_manager();
        for _ in 0..3 {
            apply_scroll_adjustment(
                &mut sm,
                dom_id(0),
                nid(INNER),
                pos(100.0, 100.0),
                ScrollIntoViewBehavior::Instant,
                now(),
            );
        }
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(
            close(offset.x, 300.0) && close(offset.y, 300.0),
            "{offset:?}"
        );
    }
    // ==================================================================
    // get_node_rect — missing / stale / corrupt layout data
    // ==================================================================
    #[test]
    fn get_node_rect_missing_dom_is_none() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        assert!(get_node_rect(dnid(0, TARGET), &empty).is_none());
    }
    #[test]
    fn get_node_rect_wrong_dom_id_is_none() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), Some(size(30.0, 40.0)))],
        ));
        assert!(get_node_rect(dnid(7, TARGET), &lrs).is_none());
    }
    #[test]
    fn get_node_rect_null_node_id_is_none() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), Some(size(30.0, 40.0)))],
        ));
        assert!(get_node_rect(null_dnid(0), &lrs).is_none());
    }
    #[test]
    fn get_node_rect_unmapped_node_is_none() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), Some(size(30.0, 40.0)))],
        ));
        assert!(get_node_rect(dnid(0, OUTER), &lrs).is_none());
        assert!(get_node_rect(dnid(0, OUT_OF_RANGE), &lrs).is_none());
    }
    #[test]
    fn get_node_rect_empty_layout_index_list_is_none() {
        let mut lr = layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), Some(size(30.0, 40.0)))],
        );
        // A DOM node mapped to *no* layout box (can happen for display:none).
        lr.layout_tree.dom_to_layout.insert(nid(TARGET), Vec::new());
        assert!(get_node_rect(dnid(0, TARGET), &window(lr)).is_none());
    }
    #[test]
    fn get_node_rect_dangling_layout_index_is_none_not_a_panic() {
        let mut lr = layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), Some(size(30.0, 40.0)))],
        );
        // Stale mapping pointing past the end of both `calculated_positions` and
        // `layout_tree.nodes` — must be a None, not an out-of-bounds index panic.
        lr.layout_tree
            .dom_to_layout
            .insert(nid(TARGET), vec![LayoutNodeId::new(7)]);
        assert!(get_node_rect(dnid(0, TARGET), &window(lr)).is_none());
    }
    #[test]
    fn get_node_rect_unsized_node_is_none() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), None)],
        ));
        assert!(get_node_rect(dnid(0, TARGET), &lrs).is_none());
    }
    #[test]
    fn get_node_rect_returns_position_and_used_size() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(10.0, 20.0), Some(size(30.0, 40.0)))],
        ));
        let r = get_node_rect(dnid(0, TARGET), &lrs).expect("target has a layout box");
        assert!(close(r.origin.x, 10.0) && close(r.origin.y, 20.0));
        assert!(close(r.size.width, 30.0) && close(r.size.height, 40.0));
    }
    // ==================================================================
    // check_if_scrollable — predicate invariants
    // ==================================================================
    #[test]
    fn check_if_scrollable_out_of_range_node_is_none() {
        let lr = layout_result(chain_dom(SCROLL_CSS));
        let sm = ScrollManager::new();
        assert!(check_if_scrollable(dom_id(0), nid(OUT_OF_RANGE), &lr, &sm).is_none());
    }
    #[test]
    fn check_if_scrollable_without_overflow_css_is_none() {
        // Registered *and* overflowing, but the CSS says the node does not scroll.
        let lr = layout_result(chain_dom(NO_CSS));
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(500.0, 500.0),
        );
        assert!(check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm).is_none());
    }
    #[test]
    fn check_if_scrollable_without_scroll_state_is_none() {
        // CSS says scrollable, but the scroll manager has never seen the node.
        let lr = layout_result(chain_dom(SCROLL_CSS));
        let sm = ScrollManager::new();
        assert!(check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm).is_none());
    }
    #[test]
    fn check_if_scrollable_with_content_that_fits_is_none() {
        let lr = layout_result(chain_dom(SCROLL_CSS));
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 100.0),
        );
        assert!(check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm).is_none());
    }
    #[test]
    fn check_if_scrollable_reports_the_overflowing_axes_and_visible_rect() {
        let lr = layout_result(chain_dom(SCROLL_CSS));
        let mut sm = ScrollManager::new();
        // Container at (5, 7), overflowing vertically only.
        register(
            &mut sm,
            INNER,
            rect(5.0, 7.0, 100.0, 100.0),
            size(100.0, 1000.0),
        );
        sm.set_scroll_position(dom_id(0), nid(INNER), pos(0.0, 300.0), now());
        let ancestor = check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm)
            .expect("an overflowing scroll container");
        assert_eq!(ancestor.node_id, nid(INNER));
        assert_eq!(ancestor.dom_id, dom_id(0));
        assert!(
            !ancestor.scroll_x,
            "x does not overflow, so it is not scrollable"
        );
        assert!(ancestor.scroll_y);
        // visible_rect = container origin + current scroll offset, container size.
        assert!(close(ancestor.visible_rect.origin.x, 5.0));
        assert!(close(ancestor.visible_rect.origin.y, 307.0));
        assert!(close(ancestor.visible_rect.size.width, 100.0));
        assert!(close(ancestor.visible_rect.size.height, 100.0));
    }
    #[test]
    fn check_if_scrollable_uses_virtual_scroll_size_over_content_rect() {
        let lr = layout_result(chain_dom(SCROLL_CSS));
        let mut sm = ScrollManager::new();
        // Content fits the container exactly => no overflow from `content_rect`...
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 100.0),
        );
        assert!(check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm).is_none());
        // ...but a VirtualView reports a much larger virtual size, which wins.
        sm.update_virtual_scroll_bounds(dom_id(0), nid(INNER), size(100.0, 10_000.0), None);
        let ancestor = check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm)
            .expect("virtual_scroll_size must drive the overflow check");
        assert!(ancestor.scroll_y);
        assert!(!ancestor.scroll_x);
    }
    #[test]
    fn check_if_scrollable_zero_sized_container_with_content_overflows() {
        let lr = layout_result(chain_dom(SCROLL_CSS));
        let mut sm = ScrollManager::new();
        register(&mut sm, INNER, LogicalRect::zero(), size(1.0, 1.0));
        let ancestor =
            check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm).expect("1px > 0px overflows");
        assert!(ancestor.scroll_x && ancestor.scroll_y);
    }
    #[test]
    fn check_if_scrollable_x_only_css_does_not_enable_the_y_axis() {
        // `.inner` declares only `overflow-x: scroll`. Per CSS Overflow 3 § 3.1 the
        // computed `overflow-y` of such a box becomes `auto` (i.e. scrollable), and
        // `MultiValue::<LayoutOverflow>::resolve_computed` implements exactly that —
        // but `check_if_scrollable` reads the *specified* values, so the y axis stays
        // non-scrollable here even though the content overflows it.
        let lr = layout_result(chain_dom(X_ONLY_CSS));
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(500.0, 500.0),
        );
        let ancestor = check_if_scrollable(dom_id(0), nid(INNER), &lr, &sm)
            .expect("overflow-x: scroll + overflowing content");
        assert!(ancestor.scroll_x);
        assert!(!ancestor.scroll_y);
    }
    // ==================================================================
    // find_scrollable_ancestors
    // ==================================================================
    #[test]
    fn find_ancestors_missing_dom_is_empty() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        let sm = ScrollManager::new();
        assert!(find_scrollable_ancestors(dom_id(0), nid(TARGET), &empty, &sm, &no_hop).is_empty());
    }
    #[test]
    fn find_ancestors_out_of_range_node_is_empty() {
        let (lrs, sm) = inner_only();
        assert!(
            find_scrollable_ancestors(dom_id(0), nid(OUT_OF_RANGE), &lrs, &sm, &no_hop).is_empty()
        );
    }
    #[test]
    fn find_ancestors_of_the_root_is_empty() {
        // The root has no parent — the walk must terminate immediately.
        let (lrs, sm) = inner_only();
        assert!(find_scrollable_ancestors(dom_id(0), nid(0), &lrs, &sm, &no_hop).is_empty());
    }
    /// A node inside a `VirtualView`'s nested dom must be revealed through the
    /// containers that clip the HOST, not just the ones in its own dom.
    ///
    /// The walk used to stop at the nested dom's root, so a caret inside a
    /// virtualized view could never be scrolled into view through the outer
    /// page — and the geometry it did find was compared against a target rect
    /// still expressed in the nested dom's 0-relative space.
    #[test]
    fn the_walk_crosses_into_the_host_dom_and_carries_the_lift() {
        let (mut lrs, sm) = inner_only();
        // A second dom standing in for the VirtualView's nested content, hosted
        // by INNER (a live scroll container) in dom 0.
        let nested = dom_id(1);
        let nested_lr = layout_result(chain_dom(SCROLL_CSS));
        lrs.insert(nested, nested_lr);
        let lift = LogicalPosition::new(11.0, 220.0);
        let hop = move |d: DomId| {
            if d == nested {
                Some((dom_id(0), nid(INNER), lift))
            } else {
                None
            }
        };
        let ancestors = find_scrollable_ancestors(nested, nid(TARGET), &lrs, &sm, &hop);
        let crossed = ancestors
            .iter()
            .find(|a| a.dom_id == dom_id(0) && a.node_id == nid(INNER))
            .expect("the host's scroll container must be reached from the nested dom");
        assert_eq!(
            crossed.target_lift, lift,
            "the target must be lifted into the host's space before it is compared"
        );
        // And nothing found INSIDE the nested dom is lifted.
        assert!(
            ancestors
                .iter()
                .filter(|a| a.dom_id == nested)
                .all(|a| a.target_lift == LogicalPosition::zero()),
            "geometry in the target's own dom needs no lift"
        );
    }
    #[test]
    fn find_ancestors_excludes_the_target_itself() {
        // `.inner` is a live scroll container, but scrolling *itself* into view is
        // not the job of its own scrollport: the walk starts at the parent.
        let (lrs, sm) = inner_only();
        let ancestors = find_scrollable_ancestors(dom_id(0), nid(INNER), &lrs, &sm, &no_hop);
        assert!(ancestors.iter().all(|a| a.node_id != nid(INNER)));
    }
    #[test]
    fn find_ancestors_skips_styled_but_non_overflowing_containers() {
        // `.outer` is styled `overflow: scroll` but was never registered.
        let (lrs, sm) = inner_only();
        let ancestors = find_scrollable_ancestors(dom_id(0), nid(TARGET), &lrs, &sm, &no_hop);
        assert_eq!(ancestors.len(), 1);
        assert_eq!(ancestors[0].node_id, nid(INNER));
    }
    #[test]
    fn find_ancestors_orders_innermost_first() {
        let lrs = window(layout_result(chain_dom(SCROLL_CSS)));
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 400.0, 100.0, 100.0),
            size(100.0, 1000.0),
        );
        register(
            &mut sm,
            OUTER,
            rect(0.0, 0.0, 200.0, 200.0),
            size(200.0, 2000.0),
        );
        let ancestors = find_scrollable_ancestors(dom_id(0), nid(TARGET), &lrs, &sm, &no_hop);
        assert_eq!(ancestors.len(), 2);
        assert_eq!(
            ancestors[0].node_id,
            nid(INNER),
            "innermost must come first"
        );
        assert_eq!(ancestors[1].node_id, nid(OUTER));
    }
    // ==================================================================
    // scroll_rect_into_view — the core primitive
    // ==================================================================
    #[test]
    fn rect_into_view_without_scroll_containers_is_a_no_op() {
        let lrs = window(layout_result(chain_dom(SCROLL_CSS)));
        let mut sm = ScrollManager::new();
        let adjustments = scroll_rect_into_view(
            rect(0.0, 5000.0, 10.0, 10.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert!(adjustments.is_empty());
        assert!(sm.get_current_offset(dom_id(0), nid(INNER)).is_none());
    }
    #[test]
    fn rect_into_view_missing_dom_is_a_no_op() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        let mut sm = ScrollManager::new();
        let adjustments = scroll_rect_into_view(
            rect(0.0, 5000.0, 10.0, 10.0),
            dom_id(0),
            nid(TARGET),
            &empty,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        );
        assert!(adjustments.is_empty());
    }
    #[test]
    fn rect_into_view_already_visible_target_does_not_scroll() {
        let (lrs, mut sm) = inner_only();
        let adjustments = scroll_rect_into_view(
            rect(0.0, 10.0, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        );
        assert!(adjustments.is_empty());
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn rect_into_view_scrolls_and_reports_the_delta() {
        let (lrs, mut sm) = inner_only();
        let adjustments = scroll_rect_into_view(
            rect(0.0, 500.0, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        assert_eq!(adjustments[0].scroll_container_node_id, nid(INNER));
        assert!(close(adjustments[0].delta.y, 500.0));
        assert_eq!(adjustments[0].delta.x, 0.0, "x does not overflow");
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.y, 500.0), "{offset:?}");
    }
    #[test]
    fn rect_into_view_ignores_a_delta_at_exactly_the_threshold() {
        // The guard is `abs() > SCROLL_DELTA_THRESHOLD`, so a delta of exactly
        // 0.5px is *not* applied. 0.5 and 0.75 are both exact in binary f32.
        assert!(close(SCROLL_DELTA_THRESHOLD, 0.5));
        let (lrs, mut sm) = inner_only();
        let at_threshold = scroll_rect_into_view(
            rect(0.0, 0.5, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert!(at_threshold.is_empty(), "0.5px must be below the threshold");
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!(offset.y, 0.0);
        let above_threshold = scroll_rect_into_view(
            rect(0.0, 0.75, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(above_threshold.len(), 1, "0.75px must scroll");
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.y, 0.75), "{offset:?}");
    }
    #[test]
    fn rect_into_view_f32_max_rect_clamps_to_max_scroll() {
        let (lrs, mut sm) = inner_only();
        let adjustments = scroll_rect_into_view(
            rect(f32::MAX, f32::MAX, f32::MAX, f32::MAX),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        // max scroll y = content 1000 - container 100
        assert!(close(offset.y, 900.0), "{offset:?}");
    }
    #[test]
    fn rect_into_view_nan_rect_does_not_scroll_or_poison_the_offset() {
        let (lrs, mut sm) = inner_only();
        let adjustments = scroll_rect_into_view(
            LogicalRect::new(pos(f32::NAN, f32::NAN), size(f32::NAN, f32::NAN)),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        // `NaN.abs() > threshold` is false, so the adjustment is skipped entirely.
        assert!(adjustments.is_empty());
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn rect_into_view_negative_rect_scrolls_back_and_clamps_at_zero() {
        let (lrs, mut sm) = inner_only();
        sm.set_scroll_position(dom_id(0), nid(INNER), pos(0.0, 300.0), now());
        let adjustments = scroll_rect_into_view(
            rect(0.0, -500.0, 10.0, 10.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        // visible rect starts at y = 0 + 300, so the reported delta is unclamped...
        assert!(
            close(adjustments[0].delta.y, -800.0),
            "{:?}",
            adjustments[0]
        );
        // ...while the stored offset is clamped into [0, max_scroll].
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!(offset.y, 0.0);
    }
    #[test]
    fn rect_into_view_auto_behavior_is_resolved_to_instant() {
        let (lrs, mut sm) = inner_only();
        let adjustments = scroll_rect_into_view(
            rect(0.0, 500.0, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Auto,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        assert_eq!(adjustments[0].behavior, ScrollIntoViewBehavior::Instant);
        assert!(!sm.has_active_animations());
    }
    #[test]
    fn rect_into_view_smooth_behavior_animates() {
        let (lrs, mut sm) = inner_only();
        let adjustments = scroll_rect_into_view(
            rect(0.0, 500.0, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Smooth,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        assert_eq!(adjustments[0].behavior, ScrollIntoViewBehavior::Smooth);
        assert!(sm.has_active_animations());
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!(offset.y, 0.0, "a smooth scroll must not jump");
    }
    #[test]
    fn rect_into_view_walks_the_whole_scroll_chain_innermost_first() {
        let lrs = window(layout_result(chain_dom(SCROLL_CSS)));
        let mut sm = ScrollManager::new();
        // `.inner` sits at absolute y=400 inside `.outer`, which is itself scrolled
        // to the top. The target is deep inside `.inner`'s content at y=900.
        register(
            &mut sm,
            INNER,
            rect(0.0, 400.0, 100.0, 100.0),
            size(100.0, 1000.0),
        );
        register(
            &mut sm,
            OUTER,
            rect(0.0, 0.0, 200.0, 200.0),
            size(200.0, 2000.0),
        );
        let adjustments = scroll_rect_into_view(
            rect(0.0, 900.0, 50.0, 20.0),
            dom_id(0),
            nid(TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 2);
        assert_eq!(adjustments[0].scroll_container_node_id, nid(INNER));
        assert_eq!(adjustments[1].scroll_container_node_id, nid(OUTER));
        // inner: target 900 - visible 400 => 500
        assert!(close(adjustments[0].delta.y, 500.0), "{:?}", adjustments[0]);
        // outer: the rect is re-based by the inner scroll (900 - 500 = 400), so the
        // outer container only has to scroll the remaining 400.
        assert!(close(adjustments[1].delta.y, 400.0), "{:?}", adjustments[1]);
        let inner_offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        let outer_offset = sm.get_current_offset(dom_id(0), nid(OUTER)).unwrap();
        assert!(close(inner_offset.y, 500.0), "{inner_offset:?}");
        assert!(close(outer_offset.y, 400.0), "{outer_offset:?}");
    }
    // ==================================================================
    // scroll_node_into_view
    // ==================================================================
    #[test]
    fn node_into_view_missing_layout_results_is_empty() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        let mut sm = ScrollManager::new();
        assert!(scroll_node_into_view(
            dnid(0, TARGET),
            &empty,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        )
        .is_empty());
    }
    #[test]
    fn node_into_view_null_node_is_empty() {
        let (lrs, mut sm) = inner_only();
        assert!(scroll_node_into_view(
            null_dnid(0),
            &lrs,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        )
        .is_empty());
    }
    #[test]
    fn node_into_view_without_a_layout_box_is_empty() {
        // `inner_only()` has an empty layout tree, so `get_node_rect` finds nothing.
        let (lrs, mut sm) = inner_only();
        assert!(scroll_node_into_view(
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            ScrollIntoViewOptions::center(),
            now(),
            &no_hop,
        )
        .is_empty());
    }
    #[test]
    fn node_into_view_scrolls_the_nodes_bounding_rect() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(0.0, 500.0), Some(size(50.0, 20.0)))],
        ));
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 1000.0),
        );
        let adjustments = scroll_node_into_view(
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.y, 500.0), "{offset:?}");
    }
    #[test]
    fn node_into_view_center_alignment_centers_the_node() {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(0.0, 500.0), Some(size(50.0, 20.0)))],
        ));
        let mut sm = ScrollManager::new();
        register(
            &mut sm,
            INNER,
            rect(0.0, 0.0, 100.0, 100.0),
            size(100.0, 1000.0),
        );
        let adjustments = scroll_node_into_view(
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Center,
                ScrollLogicalPosition::Center,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        // target center 510, container center 50 => 460
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.y, 460.0), "{offset:?}");
    }
    // ==================================================================
    // scroll_cursor_into_view — numeric
    // ==================================================================
    /// `.target` is a 100×1000 text box filling `.inner`'s content area.
    fn cursor_fixture(content: LogicalSize) -> (BTreeMap<DomId, DomLayoutResult>, ScrollManager) {
        let lrs = window(layout_result_with_boxes(
            chain_dom(SCROLL_CSS),
            &[(TARGET, pos(0.0, 0.0), Some(size(100.0, 1000.0)))],
        ));
        let mut sm = ScrollManager::new();
        register(&mut sm, INNER, rect(0.0, 0.0, 100.0, 100.0), content);
        (lrs, sm)
    }
    #[test]
    fn cursor_into_view_missing_node_is_empty() {
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        let mut sm = ScrollManager::new();
        assert!(scroll_cursor_into_view(
            rect(0.0, 800.0, 2.0, 16.0),
            dnid(0, TARGET),
            &empty,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        )
        .is_empty());
    }
    #[test]
    fn cursor_into_view_null_node_is_empty() {
        let (lrs, mut sm) = cursor_fixture(size(100.0, 1000.0));
        assert!(scroll_cursor_into_view(
            rect(0.0, 800.0, 2.0, 16.0),
            null_dnid(0),
            &lrs,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        )
        .is_empty());
    }
    #[test]
    fn cursor_into_view_zero_rect_maps_to_the_node_origin() {
        // The node origin is the container origin, so a zero cursor rect there is
        // already visible and nothing scrolls.
        let (lrs, mut sm) = cursor_fixture(size(100.0, 1000.0));
        let adjustments = scroll_cursor_into_view(
            LogicalRect::zero(),
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            ScrollIntoViewOptions::nearest(),
            now(),
            &no_hop,
        );
        assert!(adjustments.is_empty());
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn cursor_into_view_transforms_local_coordinates_to_absolute() {
        let (lrs, mut sm) = cursor_fixture(size(100.0, 1000.0));
        // Cursor at node-local (0, 800) => absolute (0, 800).
        let adjustments = scroll_cursor_into_view(
            rect(0.0, 800.0, 2.0, 16.0),
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.y, 800.0), "{offset:?}");
    }
    #[test]
    fn cursor_into_view_scrolls_back_up_to_a_cursor_above_the_viewport() {
        let (lrs, mut sm) = cursor_fixture(size(100.0, 1000.0));
        sm.set_scroll_position(dom_id(0), nid(INNER), pos(0.0, 300.0), now());
        let adjustments = scroll_cursor_into_view(
            rect(0.0, 50.0, 2.0, 16.0),
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        // visible rect starts at 300, cursor at 50 => delta -250 => offset 50
        assert!(
            close(adjustments[0].delta.y, -250.0),
            "{:?}",
            adjustments[0]
        );
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(close(offset.y, 50.0), "{offset:?}");
    }
    #[test]
    fn cursor_into_view_nan_cursor_rect_does_not_scroll_or_panic() {
        let (lrs, mut sm) = cursor_fixture(size(100.0, 1000.0));
        let adjustments = scroll_cursor_into_view(
            LogicalRect::new(pos(f32::NAN, f32::NAN), size(2.0, 16.0)),
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert!(adjustments.is_empty());
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        assert_eq!((offset.x, offset.y), (0.0, 0.0));
    }
    #[test]
    fn cursor_into_view_f32_max_cursor_clamps_to_max_scroll_on_both_axes() {
        // 500×1000 of content in a 100×100 container => max scroll (400, 900).
        let (lrs, mut sm) = cursor_fixture(size(500.0, 1000.0));
        let adjustments = scroll_cursor_into_view(
            LogicalRect::new(pos(f32::MAX, f32::MAX), size(2.0, 16.0)),
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Start,
                ScrollLogicalPosition::Start,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        assert_eq!(adjustments.len(), 1);
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        assert!(
            close(offset.x, 400.0) && close(offset.y, 900.0),
            "{offset:?}"
        );
    }
    #[test]
    fn cursor_into_view_infinite_cursor_rect_does_not_panic() {
        let (lrs, mut sm) = cursor_fixture(size(500.0, 1000.0));
        let adjustments = scroll_cursor_into_view(
            LogicalRect::new(
                pos(f32::NEG_INFINITY, f32::INFINITY),
                size(f32::INFINITY, f32::INFINITY),
            ),
            dnid(0, TARGET),
            &lrs,
            &mut sm,
            opts(
                ScrollLogicalPosition::Nearest,
                ScrollLogicalPosition::Nearest,
                ScrollIntoViewBehavior::Instant,
            ),
            now(),
            &no_hop,
        );
        // Whatever it decides, the stored offset must stay inside the bounds.
        let _ = adjustments;
        let offset = sm.get_current_offset(dom_id(0), nid(INNER)).unwrap();
        assert!(offset.x.is_finite() && offset.y.is_finite(), "{offset:?}");
        assert!(offset.x >= 0.0 && offset.x <= 400.0, "{offset:?}");
        assert!(offset.y >= 0.0 && offset.y <= 900.0, "{offset:?}");
    }
}
/// `Nearest` means the MINIMUM scroll that reveals the target — and a target
/// already on screen needs none, even when it is taller than the scrollport.
#[cfg(test)]
mod nearest_oversized_tests {
    use azul_core::events::ScrollLogicalPosition::{Nearest, Start};
    use super::calculate_axis_delta;
    /// THE BUG: AzWriter's contenteditable is 929px tall, starts 113px down
    /// the page (its top margin) and sits in a 357px viewport. `Nearest` fell
    /// through to "align the target's start", scrolling the top margin off and
    /// jamming the caret against the top edge of a freshly opened document.
    ///
    /// NEGATIVE CONTROL: drop the oversized-and-visible early-out and this
    /// returns 113.
    #[test]
1
    fn an_oversized_target_that_is_already_on_screen_does_not_scroll() {
1
        assert_eq!(
1
            calculate_axis_delta(113.0, 929.0, 0.0, 357.0, Nearest),
            0.0,
            "the page's top margin must survive focusing the editable"
        );
        // Explicit `Start` still means start — only `Nearest` got smarter.
1
        assert_eq!(calculate_axis_delta(113.0, 929.0, 0.0, 357.0, Start), 113.0);
1
    }
    /// An oversized target ENTIRELY off screen is still pulled in — the
    /// early-out is about "already visible", not about size alone.
    #[test]
1
    fn an_oversized_target_that_is_off_screen_is_still_revealed() {
        // Entirely below the scrollport.
1
        assert_eq!(
1
            calculate_axis_delta(500.0, 900.0, 0.0, 357.0, Nearest),
            500.0
        );
        // Entirely above it.
1
        assert_eq!(
1
            calculate_axis_delta(-1000.0, 900.0, 0.0, 357.0, Nearest),
            -1000.0
        );
1
    }
    /// Targets that FIT keep the classic minimum-scroll behaviour.
    #[test]
1
    fn a_fitting_target_is_unaffected() {
        // Already visible → no scroll.
1
        assert_eq!(calculate_axis_delta(50.0, 100.0, 0.0, 357.0, Nearest), 0.0);
        // Below → align its end with the container's end.
1
        assert_eq!(
1
            calculate_axis_delta(400.0, 100.0, 0.0, 357.0, Nearest),
            143.0
        );
        // Above → align its start.
1
        assert_eq!(
1
            calculate_axis_delta(-50.0, 100.0, 0.0, 357.0, Nearest),
            -50.0
        );
1
    }
}