nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Layer-1 Engine CSS Scroll Anchoring (`overflow-anchor: auto`) for [`super::LaidOutScene`].
//!
//! Captures one pre-layout live visible in-flow anchor child per scrolled container right before
//! `compute_layout`, descending through partially-clipped in-flow wrapper boxes (such as
//! `scrollview > view.column > [msg...]`) and skipping newly inserted nodes, `Overlay` nodes,
//! `display: none`, and `Position::{Absolute, Fixed, Sticky}`.
//!
//! Immediately after layout, `reconcile_scroll_offsets` compensates `(sx, sy)` by the anchor's
//! container-relative position delta before clamping whenever `requested_scroll_seq` did not seek
//! this frame, keeping visible content pinned with zero 1-frame jump and zero steady-state allocs.

use nativeview_engine::LayoutRect;
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::{Display, Overflow, OverflowAnchor, Overlay, Position, Scroll};
use nativeview_tables::semantics::SemanticStyleOracle;

use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};

use super::super::LaidOutScene;
use super::super::style_cascade::StackingStyle;
use super::{ScrollOffsets, scroll_axes_allow};
use nativeview_tables::semantics::is_subtree_closed_overlay;

const ANCHOR_AXIS_X: u8 = 1 << 0;
const ANCHOR_AXIS_Y: u8 = 1 << 1;

/// Pre-layout container-relative anchor snapshot (`Copy`, 20 B, stored in reusable `Vec`).
#[derive(Debug, Clone, Copy)]
pub(crate) struct CapturedScrollAnchor {
    pub container: NodeId,
    pub anchor: NodeId,
    pub pre_rel_x: f32,
    pub pre_rel_y: f32,
    pub scrolled_axes: u8,
}

/// A scroll container or a box whose cascaded overflow clips (anchoring stops descending).
#[inline]
fn is_clip_box(store: &NodeStore, id: NodeId, style: &StackingStyle) -> bool {
    let clips = |o: Option<Overflow>| o.is_some_and(|o| o != Overflow::Visible);
    store.has::<Scroll>(id) || clips(style.overflow_x) || clips(style.overflow_y)
}

/// Returns `true` when `candidate` is still a live descendant of `ancestor` in `store`.
pub(crate) fn is_descendant_of(store: &NodeStore, candidate: NodeId, ancestor: NodeId) -> bool {
    let mut cur = store.parent(candidate);
    for _ in 0..MAX_TREE_DEPTH {
        let Some(p) = cur else {
            return false;
        };
        if p == ancestor {
            return true;
        }
        cur = store.parent(p).filter(|&next| next != p);
    }
    false
}

#[derive(Clone, Copy)]
struct AnchorSearchViewport {
    left: f32,
    right: f32,
    top: f32,
    bottom: f32,
    allow_x: bool,
    allow_y: bool,
}

impl AnchorSearchViewport {
    #[inline]
    fn intersects(&self, r: LayoutRect) -> bool {
        let vis_y = !self.allow_y || (r.y + r.height > self.top + 0.5 && r.y < self.bottom - 0.5);
        let vis_x = !self.allow_x || (r.x + r.width > self.left + 0.5 && r.x < self.right - 0.5);
        vis_x && vis_y
    }

    #[inline]
    fn fully_contains(&self, r: LayoutRect) -> bool {
        let in_y = !self.allow_y || (r.y >= self.top - 0.5 && r.y + r.height <= self.bottom + 0.5);
        let in_x = !self.allow_x || (r.x >= self.left - 0.5 && r.x + r.width <= self.right + 0.5);
        in_x && in_y
    }
}

fn find_first_visible_anchor<L: StoreLayoutEngine>(
    scene: &LaidOutScene<L>,
    store: &NodeStore,
    parent: NodeId,
    vp: AnchorSearchViewport,
    depth: usize,
) -> Option<(NodeId, LayoutRect)> {
    if depth > MAX_TREE_DEPTH {
        return None;
    }
    let cascade = scene.style_cascade();
    for &cid in store.children(parent) {
        if !store.is_live(cid) || store.is_inline(cid) || store.has::<Overlay>(cid) {
            continue;
        }
        // One cascade visit: display, position and overflow as layout and paint see them.
        let style = cascade.stacking_style(store, cid);
        match style.display {
            Display::None => continue,
            Display::Contents => {
                if let Some(found) = find_first_visible_anchor(scene, store, cid, vp, depth + 1) {
                    return Some(found);
                }
                continue;
            }
            _ => {}
        }
        // Out-of-flow boxes are never anchor candidates (CSS Scroll Anchoring 1 ยง2.2).
        if matches!(style.position, Position::Absolute | Position::Fixed | Position::Sticky) {
            continue;
        }
        let Some(r) = scene.layout.layout_of(cid) else {
            // Newly inserted nodes lack a pre-layout rect and must be skipped.
            continue;
        };
        if (r.width <= 0.0 && r.height <= 0.0) || !vp.intersects(r) {
            continue;
        }
        // CSS Scroll Anchoring Level 1 ยง2.2: descend through partially-visible unclipped in-flow
        // wrapper boxes (e.g. `scrollview > column > items`), stopping at scroll or clipping boxes.
        if !vp.fully_contains(r)
            && !is_clip_box(store, cid, &style)
            && !store.children(cid).is_empty()
            && let Some(inner) = find_first_visible_anchor(scene, store, cid, vp, depth + 1)
        {
            return Some(inner);
        }
        return Some((cid, r));
    }
    None
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Captures pre-layout scroll anchors for every live scrolled container with
    /// `Scroll::overflow_anchor == OverflowAnchor::Auto` right before `compute_layout`.
    /// O(1) no-op when no container is currently scrolled; 0 steady-state heap allocations.
    pub fn capture_scroll_anchors(&mut self, store: &NodeStore) {
        self.scroll.captured_anchors.clear();
        if self.scroll.offsets_is_empty() {
            return;
        }
        let mut captured = std::mem::take(&mut self.scroll.captured_anchors);
        for (container, (sx, sy)) in self.scroll.iter() {
            if !store.is_live(container)
                || self.style_cascade().is_subtree_display_none(store, container)
                || is_subtree_closed_overlay(store, container)
            {
                continue;
            }
            let Some(sc) = store.try_row::<Scroll>(container) else {
                continue;
            };
            if sc.overflow_anchor() == OverflowAnchor::None {
                continue;
            }
            let (allow_x, allow_y) = scroll_axes_allow(store, container);
            let scrolled_x = allow_x && sx > 0.5;
            let scrolled_y = allow_y && sy > 0.5;
            if !scrolled_x && !scrolled_y {
                continue;
            }
            let Some(vp_rect) = self.layout.layout_of(container) else {
                continue;
            };
            let (shift_x, shift_y) = ScrollOffsets::visual_shift_with(store, container, sx, sy);
            let search_vp = AnchorSearchViewport {
                left: vp_rect.x + shift_x,
                right: vp_rect.x + shift_x + vp_rect.width,
                top: vp_rect.y + shift_y,
                bottom: vp_rect.y + shift_y + vp_rect.height,
                allow_x: scrolled_x,
                allow_y: scrolled_y,
            };
            if let Some((anchor, r)) =
                find_first_visible_anchor(self, store, container, search_vp, 0)
            {
                let scrolled_axes = (if scrolled_x { ANCHOR_AXIS_X } else { 0 })
                    | (if scrolled_y { ANCHOR_AXIS_Y } else { 0 });
                captured.push(CapturedScrollAnchor {
                    container,
                    anchor,
                    pre_rel_x: r.x - vp_rect.x,
                    pre_rel_y: r.y - vp_rect.y,
                    scrolled_axes,
                });
            }
        }
        self.scroll.captured_anchors = captured;
    }

    /// Computes post-layout scroll anchor compensation `(dx, dy)` for `container` from its
    /// pre-layout anchor snapshot (if captured and still a live descendant).
    #[inline]
    pub(crate) fn scroll_anchor_delta(
        &self,
        store: &NodeStore,
        container: NodeId,
        new_vp_rect: LayoutRect,
        allow_x: bool,
        allow_y: bool,
    ) -> (f32, f32) {
        let Some(cap) = self
            .scroll
            .captured_anchors
            .iter()
            .find(|c| c.container == container)
        else {
            return (0.0, 0.0);
        };
        if !store.is_live(cap.anchor)
            || self.style_cascade().is_subtree_display_none(store, cap.anchor)
            || is_subtree_closed_overlay(store, cap.anchor)
            || !is_descendant_of(store, cap.anchor, container)
        {
            return (0.0, 0.0);
        }
        let Some(new_r) = self.layout.layout_of(cap.anchor) else {
            return (0.0, 0.0);
        };
        let dx = (new_r.x - new_vp_rect.x) - cap.pre_rel_x;
        let dy = (new_r.y - new_vp_rect.y) - cap.pre_rel_y;
        let active_x = allow_x && (cap.scrolled_axes & ANCHOR_AXIS_X) != 0;
        let active_y = allow_y && (cap.scrolled_axes & ANCHOR_AXIS_Y) != 0;
        (
            if active_x && dx.is_finite() && dx.abs() > 0.5 {
                dx
            } else {
                0.0
            },
            if active_y && dy.is_finite() && dy.abs() > 0.5 {
                dy
            } else {
                0.0
            },
        )
    }
}