nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Nested scroll chaining (`OverscrollBehavior::{Auto, Contain, None}`), per-axis `Scroll::axes`
//! enforcement, top-layer isolation, and zero-allocation delegation to the active
//! [`ScrollPhysicsEngine`].

use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::{OverscrollBehavior, Scroll};

use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};

use super::super::{LaidOutScene, cascade_of};
use super::engine::{
    ScrollAxis, ScrollBoundsLookup, ScrollContainerCtx, ScrollDeltaResult, ScrollInputKind,
    ScrollTimestampMs, ScrollTouchPhase,
};
use super::extent::compute_scroll_content_size;
use super::{ScrollChainOutcome, scroll_axes_allow};

/// Appends `id` to `buf` if not already present (O(n) deduplication for tiny dirty lists).
#[inline]
pub fn push_unique_node(buf: &mut Vec<NodeId>, id: NodeId) {
    if !buf.contains(&id) {
        buf.push(id);
    }
}

#[derive(Clone, Copy)]
struct AutoOverscrollTarget {
    node: NodeId,
    viewport: (f32, f32),
    offset: (f32, f32),
    max_offset: (f32, f32),
    allow_axes: (bool, bool),
    overscroll_behavior: (OverscrollBehavior, OverscrollBehavior),
    bounce_requested: bool,
}

impl AutoOverscrollTarget {
    #[inline]
    fn as_ctx<'a>(&self, store: &'a NodeStore) -> ScrollContainerCtx<'a> {
        ScrollContainerCtx {
            store,
            node: self.node,
            viewport: self.viewport,
            offset: self.offset,
            max_offset: self.max_offset,
            allow_axes: self.allow_axes,
            overscroll_behavior: self.overscroll_behavior,
            bounce_requested: self.bounce_requested,
        }
    }
}

pub(crate) struct SceneScrollBounds<'a, L: StoreLayoutEngine> {
    pub(crate) layout: &'a L,
    pub(crate) interaction: &'a nativeview_engine::InteractionTracker,
    pub(crate) overlays: &'a super::super::OverlayState,
}

impl<L: StoreLayoutEngine> ScrollBoundsLookup for SceneScrollBounds<'_, L> {
    fn scroll_bounds(&self, store: &NodeStore, id: NodeId) -> Option<(f32, f32, f32, f32)> {
        let rect = self.layout.layout_of(id)?;
        let cascade = cascade_of(self.layout, self.interaction);
        let (cw, ch) = compute_scroll_content_size(
            store,
            |n| self.layout.layout_of(n),
            |n| cascade.display(store, n),
            id,
        )
        .unwrap_or((rect.width, rect.height));
        let (allow_x, allow_y) = scroll_axes_allow(store, id);
        let max_x = if allow_x {
            (cw - rect.width).max(0.0)
        } else {
            0.0
        };
        let max_y = if allow_y {
            (ch - rect.height).max(0.0)
        } else {
            0.0
        };
        Some((rect.width.max(1.0), rect.height.max(1.0), max_x, max_y))
    }

    #[inline]
    fn is_top_layer_boundary(&self, node: NodeId) -> bool {
        self.overlays.get(node).is_some()
    }
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Walks from `start` up through ancestor `Scroll` containers to `NodeId::ROOT`, enforcing
    /// `Scroll::axes`, per-axis `OverscrollBehavior::{Auto, Contain, None}`, and top-layer
    /// containment, and delegating per-axis consumption, overscroll, wheel smoothing, and gesture
    /// transitions to the active [`ScrollPhysicsEngine`] (0 steady-state allocs).
    pub fn apply_scroll_chain(
        &mut self,
        store: &NodeStore,
        start: NodeId,
        dx: f32,
        dy: f32,
        kind: ScrollInputKind,
    ) -> ScrollChainOutcome {
        self.scroll.chain_changed_scratch.clear();
        self.scroll.chain_clamped_scratch.clear();
        let dx = if dx.is_finite() { dx } else { 0.0 };
        let dy = if dy.is_finite() { dy } else { 0.0 };

        let (is_smooth_px, touch_phase, now_ms) = match kind {
            ScrollInputKind::SmoothPixels {
                phase,
                timestamp_ms,
            } => (true, phase, ScrollTimestampMs::new(timestamp_ms)),
            _ => (false, ScrollTouchPhase::None, ScrollTimestampMs::new(0)),
        };

        let mut effective_start = start;
        if is_smooth_px {
            match touch_phase {
                ScrollTouchPhase::Started => {
                    let bounds = SceneScrollBounds {
                        layout: &self.layout,
                        interaction: &self.interaction,
                        overlays: &self.overlays,
                    };
                    self.scroll_physics
                        .on_gesture_start(store, &bounds, start, now_ms);
                }
                ScrollTouchPhase::Moved | ScrollTouchPhase::Ended | ScrollTouchPhase::Cancelled => {
                    if let Some(latched) = self.scroll_physics.latched_target()
                        && store.is_live(latched)
                        && store.has::<Scroll>(latched)
                        && !self.is_inert_under_modal(store, latched)
                    {
                        effective_start = latched;
                    }
                }
                ScrollTouchPhase::None => {}
            }
        }

        let mut rem_x = dx;
        let mut rem_y = dy;
        let mut consumed_x = false;
        let mut consumed_y = false;
        let mut last_auto_x: Option<AutoOverscrollTarget> = None;
        let mut last_auto_y: Option<AutoOverscrollTarget> = None;

        let mut cur = Some(effective_start);
        for _ in 0..MAX_TREE_DEPTH {
            let Some(id) = cur else {
                break;
            };
            if rem_x.abs() <= 1e-4 && rem_y.abs() <= 1e-4 {
                break;
            }
            if store.is_live(id)
                && store.has::<Scroll>(id)
                && let Some((vw, vh, max_x, max_y)) = self.scroll_bounds(store, id)
                && let Some(sc) = store.try_row::<Scroll>(id)
            {
                let allow_axes = scroll_axes_allow(store, id);
                let overscroll_behavior = (sc.overscroll_behavior_x(), sc.overscroll_behavior_y());
                let offset = self.scroll.get(id);
                let ctx = ScrollContainerCtx {
                    store,
                    node: id,
                    viewport: (vw, vh),
                    offset,
                    max_offset: (max_x, max_y),
                    allow_axes,
                    overscroll_behavior,
                    bounce_requested: sc.bounce(),
                };
                let mut res = ScrollDeltaResult {
                    next_offset: offset,
                    remaining: (rem_x, rem_y),
                    ..Default::default()
                };
                self.scroll_physics
                    .on_scroll_delta(&ctx, rem_x, rem_y, kind, &mut res);

                if res.clamped_changed {
                    self.scroll.set_raw(id, res.next_offset.0, res.next_offset.1);
                    push_unique_node(&mut self.scroll.chain_clamped_scratch, id);
                }
                if res.visual_changed {
                    push_unique_node(&mut self.scroll.chain_changed_scratch, id);
                }
                if res.auto_overscroll_x {
                    last_auto_x = Some(AutoOverscrollTarget {
                        node: id,
                        viewport: (vw, vh),
                        offset: res.next_offset,
                        max_offset: (max_x, max_y),
                        allow_axes,
                        overscroll_behavior,
                        bounce_requested: sc.bounce(),
                    });
                }
                if res.auto_overscroll_y {
                    last_auto_y = Some(AutoOverscrollTarget {
                        node: id,
                        viewport: (vw, vh),
                        offset: res.next_offset,
                        max_offset: (max_x, max_y),
                        allow_axes,
                        overscroll_behavior,
                        bounce_requested: sc.bounce(),
                    });
                }
                consumed_x |= res.consumed_x;
                consumed_y |= res.consumed_y;
                rem_x = res.remaining.0;
                rem_y = res.remaining.1;
            }
            // Stop chaining at any open top-layer overlay root so scrolling inside a dialog or
            // popover never leaks out into a background DOM ancestor scroll container.
            if self.overlays.get(id).is_some() {
                break;
            }
            cur = store.parent(id).filter(|&p| p != id);
        }

        if is_smooth_px {
            if rem_x.abs() > 1e-4
                && let Some(target) = last_auto_x
                && self.scroll_physics.on_outermost_overscroll(
                    &target.as_ctx(store),
                    ScrollAxis::X,
                    rem_x,
                    kind,
                )
            {
                push_unique_node(&mut self.scroll.chain_changed_scratch, target.node);
            }
            if rem_y.abs() > 1e-4
                && let Some(target) = last_auto_y
                && self.scroll_physics.on_outermost_overscroll(
                    &target.as_ctx(store),
                    ScrollAxis::Y,
                    rem_y,
                    kind,
                )
            {
                push_unique_node(&mut self.scroll.chain_changed_scratch, target.node);
            }

            match touch_phase {
                ScrollTouchPhase::Ended | ScrollTouchPhase::Cancelled => {
                    let mut out_visual = std::mem::take(&mut self.scroll.chain_changed_scratch);
                    let mut out_clamped = std::mem::take(&mut self.scroll.chain_clamped_scratch);
                    self.scroll_physics.on_gesture_end(
                        store,
                        &mut self.scroll,
                        now_ms,
                        touch_phase == ScrollTouchPhase::Cancelled,
                        &mut out_visual,
                        &mut out_clamped,
                    );
                    self.scroll.chain_changed_scratch = out_visual;
                    self.scroll.chain_clamped_scratch = out_clamped;
                }
                ScrollTouchPhase::Moved => {
                    self.scroll_physics.on_gesture_move(now_ms);
                }
                ScrollTouchPhase::Started | ScrollTouchPhase::None => {}
            }
        }

        ScrollChainOutcome {
            consumed_x,
            consumed_y,
            any_visual_changed: !self.scroll.chain_changed_scratch.is_empty(),
            any_clamped_changed: !self.scroll.chain_clamped_scratch.is_empty(),
            active_physics: self.scroll_physics.has_active(),
        }
    }

    /// Advances all active scroll animations in the installed [`ScrollPhysicsEngine`] by `dt_s`
    /// seconds with zero steady-state allocations. Returns `(still_active, any_visual_changed)`.
    pub fn step_scroll_physics(&mut self, store: &NodeStore, dt_s: f32) -> (bool, bool) {
        self.scroll.step_visual_scratch.clear();
        self.scroll.step_clamped_scratch.clear();
        if dt_s <= 0.0 || !dt_s.is_finite() || !self.scroll_physics.has_active() {
            return (self.scroll_physics.has_active(), false);
        }
        let mut out_visual = std::mem::take(&mut self.scroll.step_visual_scratch);
        let mut out_clamped = std::mem::take(&mut self.scroll.step_clamped_scratch);
        let bounds = SceneScrollBounds {
            layout: &self.layout,
            interaction: &self.interaction,
            overlays: &self.overlays,
        };
        let still_active = self.scroll_physics.step(
            store,
            &bounds,
            &mut self.scroll,
            dt_s,
            &mut out_visual,
            &mut out_clamped,
        );
        let any_visual = !out_visual.is_empty();
        self.scroll.step_visual_scratch = out_visual;
        self.scroll.step_clamped_scratch = out_clamped;
        (still_active, any_visual)
    }
}