Skip to main content

nativeview_layout/scene/scroll/
anchor.rs

1//! Layer-1 Engine CSS Scroll Anchoring (`overflow-anchor: auto`) for [`super::LaidOutScene`].
2//!
3//! Captures one pre-layout live visible in-flow anchor child per scrolled container right before
4//! `compute_layout`, descending through partially-clipped in-flow wrapper boxes (such as
5//! `scrollview > view.column > [msg...]`) and skipping newly inserted nodes, `Overlay` nodes,
6//! `display: none`, and `Position::{Absolute, Fixed, Sticky}`.
7//!
8//! Immediately after layout, `reconcile_scroll_offsets` compensates `(sx, sy)` by the anchor's
9//! container-relative position delta before clamping whenever `requested_scroll_seq` did not seek
10//! this frame, keeping visible content pinned with zero 1-frame jump and zero steady-state allocs.
11
12use nativeview_engine::LayoutRect;
13use nativeview_store::{NodeId, NodeStore};
14use nativeview_tables::tables::{Display, Overflow, OverflowAnchor, Overlay, Position, Scroll};
15use nativeview_tables::semantics::SemanticStyleOracle;
16
17use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};
18
19use super::super::LaidOutScene;
20use super::super::style_cascade::StackingStyle;
21use super::{ScrollOffsets, scroll_axes_allow};
22use nativeview_tables::semantics::is_subtree_closed_overlay;
23
24const ANCHOR_AXIS_X: u8 = 1 << 0;
25const ANCHOR_AXIS_Y: u8 = 1 << 1;
26
27/// Pre-layout container-relative anchor snapshot (`Copy`, 20 B, stored in reusable `Vec`).
28#[derive(Debug, Clone, Copy)]
29pub(crate) struct CapturedScrollAnchor {
30    pub container: NodeId,
31    pub anchor: NodeId,
32    pub pre_rel_x: f32,
33    pub pre_rel_y: f32,
34    pub scrolled_axes: u8,
35}
36
37/// A scroll container or a box whose cascaded overflow clips (anchoring stops descending).
38#[inline]
39fn is_clip_box(store: &NodeStore, id: NodeId, style: &StackingStyle) -> bool {
40    let clips = |o: Option<Overflow>| o.is_some_and(|o| o != Overflow::Visible);
41    store.has::<Scroll>(id) || clips(style.overflow_x) || clips(style.overflow_y)
42}
43
44/// Returns `true` when `candidate` is still a live descendant of `ancestor` in `store`.
45pub(crate) fn is_descendant_of(store: &NodeStore, candidate: NodeId, ancestor: NodeId) -> bool {
46    let mut cur = store.parent(candidate);
47    for _ in 0..MAX_TREE_DEPTH {
48        let Some(p) = cur else {
49            return false;
50        };
51        if p == ancestor {
52            return true;
53        }
54        cur = store.parent(p).filter(|&next| next != p);
55    }
56    false
57}
58
59#[derive(Clone, Copy)]
60struct AnchorSearchViewport {
61    left: f32,
62    right: f32,
63    top: f32,
64    bottom: f32,
65    allow_x: bool,
66    allow_y: bool,
67}
68
69impl AnchorSearchViewport {
70    #[inline]
71    fn intersects(&self, r: LayoutRect) -> bool {
72        let vis_y = !self.allow_y || (r.y + r.height > self.top + 0.5 && r.y < self.bottom - 0.5);
73        let vis_x = !self.allow_x || (r.x + r.width > self.left + 0.5 && r.x < self.right - 0.5);
74        vis_x && vis_y
75    }
76
77    #[inline]
78    fn fully_contains(&self, r: LayoutRect) -> bool {
79        let in_y = !self.allow_y || (r.y >= self.top - 0.5 && r.y + r.height <= self.bottom + 0.5);
80        let in_x = !self.allow_x || (r.x >= self.left - 0.5 && r.x + r.width <= self.right + 0.5);
81        in_x && in_y
82    }
83}
84
85fn find_first_visible_anchor<L: StoreLayoutEngine>(
86    scene: &LaidOutScene<L>,
87    store: &NodeStore,
88    parent: NodeId,
89    vp: AnchorSearchViewport,
90    depth: usize,
91) -> Option<(NodeId, LayoutRect)> {
92    if depth > MAX_TREE_DEPTH {
93        return None;
94    }
95    let cascade = scene.style_cascade();
96    for &cid in store.children(parent) {
97        if !store.is_live(cid) || store.is_inline(cid) || store.has::<Overlay>(cid) {
98            continue;
99        }
100        // One cascade visit: display, position and overflow as layout and paint see them.
101        let style = cascade.stacking_style(store, cid);
102        match style.display {
103            Display::None => continue,
104            Display::Contents => {
105                if let Some(found) = find_first_visible_anchor(scene, store, cid, vp, depth + 1) {
106                    return Some(found);
107                }
108                continue;
109            }
110            _ => {}
111        }
112        // Out-of-flow boxes are never anchor candidates (CSS Scroll Anchoring 1 §2.2).
113        if matches!(style.position, Position::Absolute | Position::Fixed | Position::Sticky) {
114            continue;
115        }
116        let Some(r) = scene.layout.layout_of(cid) else {
117            // Newly inserted nodes lack a pre-layout rect and must be skipped.
118            continue;
119        };
120        if (r.width <= 0.0 && r.height <= 0.0) || !vp.intersects(r) {
121            continue;
122        }
123        // CSS Scroll Anchoring Level 1 §2.2: descend through partially-visible unclipped in-flow
124        // wrapper boxes (e.g. `scrollview > column > items`), stopping at scroll or clipping boxes.
125        if !vp.fully_contains(r)
126            && !is_clip_box(store, cid, &style)
127            && !store.children(cid).is_empty()
128            && let Some(inner) = find_first_visible_anchor(scene, store, cid, vp, depth + 1)
129        {
130            return Some(inner);
131        }
132        return Some((cid, r));
133    }
134    None
135}
136
137impl<L: StoreLayoutEngine> LaidOutScene<L> {
138    /// Captures pre-layout scroll anchors for every live scrolled container with
139    /// `Scroll::overflow_anchor == OverflowAnchor::Auto` right before `compute_layout`.
140    /// O(1) no-op when no container is currently scrolled; 0 steady-state heap allocations.
141    pub fn capture_scroll_anchors(&mut self, store: &NodeStore) {
142        self.scroll.captured_anchors.clear();
143        if self.scroll.offsets_is_empty() {
144            return;
145        }
146        let mut captured = std::mem::take(&mut self.scroll.captured_anchors);
147        for (container, (sx, sy)) in self.scroll.iter() {
148            if !store.is_live(container)
149                || self.style_cascade().is_subtree_display_none(store, container)
150                || is_subtree_closed_overlay(store, container)
151            {
152                continue;
153            }
154            let Some(sc) = store.try_row::<Scroll>(container) else {
155                continue;
156            };
157            if sc.overflow_anchor() == OverflowAnchor::None {
158                continue;
159            }
160            let (allow_x, allow_y) = scroll_axes_allow(store, container);
161            let scrolled_x = allow_x && sx > 0.5;
162            let scrolled_y = allow_y && sy > 0.5;
163            if !scrolled_x && !scrolled_y {
164                continue;
165            }
166            let Some(vp_rect) = self.layout.layout_of(container) else {
167                continue;
168            };
169            let (shift_x, shift_y) = ScrollOffsets::visual_shift_with(store, container, sx, sy);
170            let search_vp = AnchorSearchViewport {
171                left: vp_rect.x + shift_x,
172                right: vp_rect.x + shift_x + vp_rect.width,
173                top: vp_rect.y + shift_y,
174                bottom: vp_rect.y + shift_y + vp_rect.height,
175                allow_x: scrolled_x,
176                allow_y: scrolled_y,
177            };
178            if let Some((anchor, r)) =
179                find_first_visible_anchor(self, store, container, search_vp, 0)
180            {
181                let scrolled_axes = (if scrolled_x { ANCHOR_AXIS_X } else { 0 })
182                    | (if scrolled_y { ANCHOR_AXIS_Y } else { 0 });
183                captured.push(CapturedScrollAnchor {
184                    container,
185                    anchor,
186                    pre_rel_x: r.x - vp_rect.x,
187                    pre_rel_y: r.y - vp_rect.y,
188                    scrolled_axes,
189                });
190            }
191        }
192        self.scroll.captured_anchors = captured;
193    }
194
195    /// Computes post-layout scroll anchor compensation `(dx, dy)` for `container` from its
196    /// pre-layout anchor snapshot (if captured and still a live descendant).
197    #[inline]
198    pub(crate) fn scroll_anchor_delta(
199        &self,
200        store: &NodeStore,
201        container: NodeId,
202        new_vp_rect: LayoutRect,
203        allow_x: bool,
204        allow_y: bool,
205    ) -> (f32, f32) {
206        let Some(cap) = self
207            .scroll
208            .captured_anchors
209            .iter()
210            .find(|c| c.container == container)
211        else {
212            return (0.0, 0.0);
213        };
214        if !store.is_live(cap.anchor)
215            || self.style_cascade().is_subtree_display_none(store, cap.anchor)
216            || is_subtree_closed_overlay(store, cap.anchor)
217            || !is_descendant_of(store, cap.anchor, container)
218        {
219            return (0.0, 0.0);
220        }
221        let Some(new_r) = self.layout.layout_of(cap.anchor) else {
222            return (0.0, 0.0);
223        };
224        let dx = (new_r.x - new_vp_rect.x) - cap.pre_rel_x;
225        let dy = (new_r.y - new_vp_rect.y) - cap.pre_rel_y;
226        let active_x = allow_x && (cap.scrolled_axes & ANCHOR_AXIS_X) != 0;
227        let active_y = allow_y && (cap.scrolled_axes & ANCHOR_AXIS_Y) != 0;
228        (
229            if active_x && dx.is_finite() && dx.abs() > 0.5 {
230                dx
231            } else {
232                0.0
233            },
234            if active_y && dy.is_finite() && dy.abs() > 0.5 {
235                dy
236            } else {
237                0.0
238            },
239        )
240    }
241}