nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Shared zero-allocation hit-test geometry over [`LaidOutScene`] driven by [`StackingPlan`]:
//! CSS 2.1 Appendix E reverse stacking walk, top-layer [`Overlay`] modal/scrim hit-blocking,
//! containing-block overflow clipping & scroll shifts, sticky clamping, `Transform2D` inverse
//! mapping (with optional animated transform override), `display: contents` flattening, and
//! DOM ancestor bubbling.

use nativeview_engine::LayoutRect;
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::layout_ext::compute_sticky_offset;
use nativeview_tables::snapshots::transform_from_patch_view;
use nativeview_tables::tables::{
    Interaction, Layout as NvLayout, Overflow, Position, Scroll, Transform as TransformTable,
    generates_box,
};
use nativeview_tables::transform::Transform2D;

use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};

pub(crate) mod helpers;
mod walk;

use helpers::{bubble_dom_ancestors, paragraph_content_insets};
use walk::PlanHitWalk;
use super::stacking::{SceneStackingStyleSource, StackingPlan};
use super::LaidOutScene;

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Nearest ancestor of `id` that generates a box (skips `display: contents` ancestors).
    fn box_parent(store: &NodeStore, id: NodeId) -> Option<NodeId> {
        let mut cur = store.parent(id);
        for _ in 0..MAX_TREE_DEPTH {
            let anc = cur?;
            if generates_box(store, anc) {
                return Some(anc);
            }
            cur = store.parent(anc);
        }
        None
    }

    /// Computes sticky offset `(dx, dy)` for `id` against its nearest scroll ancestor.
    pub fn compute_sticky_delta(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
        if !generates_box(store, id) {
            return (0.0, 0.0);
        }
        self.sticky_delta_of_box(store, id)
    }

    pub(crate) fn sticky_delta_of_box(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
        let Some(l) = store.try_row::<NvLayout>(id) else {
            return (0.0, 0.0);
        };
        // Position and insets through the cascade, in one visit.
        let (mut position, mut top, mut right, mut bottom, mut left) =
            (l.position(), l.inset_top(), l.inset_right(), l.inset_bottom(), l.inset_left());
        self.style_cascade().visit(store, id, |_, pv| {
            position = pv.get_prop(NvLayout::POSITION).unwrap_or(position);
            top = pv.get_prop(NvLayout::INSET_TOP).unwrap_or(top);
            right = pv.get_prop(NvLayout::INSET_RIGHT).unwrap_or(right);
            bottom = pv.get_prop(NvLayout::INSET_BOTTOM).unwrap_or(bottom);
            left = pv.get_prop(NvLayout::INSET_LEFT).unwrap_or(left);
        });
        if position != Position::Sticky {
            return (0.0, 0.0);
        }
        let Some(node_rect) = self.layout.layout_of(id) else {
            return (0.0, 0.0);
        };
        let Some(parent_id) = Self::box_parent(store, id) else {
            return (0.0, 0.0);
        };
        let Some(cb_rect) = self.layout.layout_of(parent_id) else {
            return (0.0, 0.0);
        };

        let mut scroller = parent_id;
        let mut cur = Some(parent_id);
        let mut scroll = (0.0f32, 0.0f32);
        let mut steps = 0usize;
        while let Some(anc) = cur {
            if steps > MAX_TREE_DEPTH {
                break;
            }
            steps += 1;
            let raw = anc;
            let has_offset = self.scroll.contains(raw);
            let is_scroll = store.has::<Scroll>(anc) || {
                let style = self.style_cascade().stacking_style(store, anc);
                let scrolls = |o: Option<Overflow>| {
                    matches!(o, Some(Overflow::Scroll | Overflow::Auto))
                };
                scrolls(style.overflow_x) || scrolls(style.overflow_y)
            };
            if has_offset || is_scroll {
                scroller = anc;
                scroll = self.compositor_scroll_offset(raw);
                break;
            }
            cur = Self::box_parent(store, anc);
        }

        let vp_rect = self.layout.layout_of(scroller).unwrap_or(LayoutRect {
            x: 0.0,
            y: 0.0,
            width: self.viewport.width,
            height: self.viewport.height,
        });
        let insets = nativeview_tables::layout_ext::PositionInsets {
            top: top.to_dimension(),
            right: right.to_dimension(),
            bottom: bottom.to_dimension(),
            left: left.to_dimension(),
        };
        compute_sticky_offset(
            (node_rect.x, node_rect.y, node_rect.width, node_rect.height),
            (cb_rect.x, cb_rect.y, cb_rect.width, cb_rect.height),
            (vp_rect.x, vp_rect.y, vp_rect.width, vp_rect.height),
            scroll,
            insets,
        )
    }

    /// Reads the `Transform2D` of `id` from `NodeStore`'s `Transform` table (including active
    /// `StateRules` overrides), if `id` generates a box.
    pub fn effective_transform(&self, store: &NodeStore, id: NodeId) -> Option<Transform2D> {
        if !generates_box(store, id) {
            return None;
        }
        let mut base = Self::transform_of_box(store, id);
        self.visit_effective_patches(store, id, |pv| {
            if let Some(tf) = transform_from_patch_view(pv) {
                base = (!tf.is_identity()).then_some(tf);
            }
        });
        base
    }

    fn transform_of_box(store: &NodeStore, id: NodeId) -> Option<Transform2D> {
        let t = store.try_row::<TransformTable>(id)?;
        let tf = Transform2D {
            translate_x: t.translate_x(),
            translate_y: t.translate_y(),
            scale_x: t.scale_x(),
            scale_y: t.scale_y(),
            rotate_deg: t.rotate_deg(),
            origin_x: t.origin_x(),
            origin_y: t.origin_y(),
        };
        (!tf.is_identity()).then_some(tf)
    }

    /// Returns `true` when `id` subscribes to any UI event via its `Interaction` table.
    #[inline]
    pub fn is_event_target(store: &NodeStore, id: NodeId) -> bool {
        store
            .try_row::<Interaction>(id)
            .is_some_and(|i| !i.listeners().is_empty())
    }

    /// Directly hit-tests local coordinates `(local_x, local_y)` inside paragraph root `para_id`'s
    /// content box, returning the hit run's leaf `NodeId` (`None` on trailing whitespace / miss).
    pub fn hit_test_paragraph_leaf(
        &self,
        store: &NodeStore,
        para_id: NodeId,
        local_x: f32,
        local_y: f32,
    ) -> Option<NodeId> {
        let para = self.paragraphs()?.paragraph_view(store, para_id)?;
        let rect = self.layout.layout_of(para_id)?;
        let (cl, _, cr, _) = paragraph_content_insets(store, para_id, rect.width);
        let content_w = (rect.width - cl - cr).max(0.0);
        self.text_measurer()
            .hit_test_paragraph(&para, content_w, local_x, local_y)
    }

    /// Returns `true` when `id` is a scroll container (it owns a `Scroll` row, which also carries
    /// its `ScrollEvent` listeners).
    #[inline]
    pub fn is_scroll_container(store: &NodeStore, id: NodeId) -> bool {
        store.has::<Scroll>(id)
    }

    /// Hit-tests `(x, y)` in reverse CSS 2.1 Appendix E paint order for the deepest node
    /// subscribing to events.
    pub fn hit_test(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_where(store, x, y, |id| Self::is_event_target(store, id))
    }

    /// The deepest painted node at `(x, y)`, unfiltered: the press hit of [`super::top_layer_press`].
    pub fn hit_test_painted(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
        self.hit_test_where(store, x, y, |_| true)
    }

    /// Hit-tests `(x, y)` in reverse CSS 2.1 Appendix E paint order for the deepest scroll
    /// container (`Scroll` row).
    pub fn hit_test_scroll_container(
        &self,
        store: &NodeStore,
        x: f32,
        y: f32,
    ) -> Option<NodeId> {
        self.hit_test_where(store, x, y, |id| Self::is_scroll_container(store, id))
    }

    /// The cache key of the stacking plan for `store`'s current commit, interaction state,
    /// overlays, and responsive (`@media` / `@container`) resolution.
    pub(crate) fn stacking_cache_key(&self, store: &NodeStore) -> super::StackingCacheKey {
        super::StackingCacheKey {
            store: store.instance_id(),
            commit_epoch: store.commit_epoch(),
            interaction_epoch: self.interaction_epoch,
            overlay_gen: self.overlays.generation(),
            responsive_epoch: self.layout.responsive_epoch(),
        }
    }

    /// Hit-tests `(x, y)` in reverse CSS 2.1 Appendix E paint order for the deepest node
    /// `accepts` admits (O(1) cached `StackingPlan`, 0 steady-state heap allocations).
    pub fn hit_test_where(
        &self,
        store: &NodeStore,
        x: f32,
        y: f32,
        accepts: impl Fn(NodeId) -> bool,
    ) -> Option<NodeId> {
        let key = self.stacking_cache_key(store);
        let mut plan = self.stacking_cache.take();
        if self.stacking_cache_has_tf_override.get()
            || self.stacking_cache_key.get() != key
            || plan.is_empty()
        {
            let style = SceneStackingStyleSource::new(self.style_cascade(), |_, base| base);
            plan.build(store, self.overlays.open_overlays(), &style);
            self.stacking_cache_key.set(key);
            self.stacking_cache_has_tf_override.set(false);
        }
        let result = self.hit_test_with_plan(store, &plan, x, y, |_, base| base, accepts);
        self.stacking_cache.set(plan);
        result
    }

    /// Hit-tests `(x, y)` using a caller-supplied pre-built [`StackingPlan`] (such as
    /// `SkiaBackend`'s retained `CompositorScene::stacking`), guaranteeing exact 1:1 paint/hit
    /// parity at O(1) zero rebuild cost and 0 heap allocations.
    pub fn hit_test_with_plan(
        &self,
        store: &NodeStore,
        plan: &StackingPlan,
        x: f32,
        y: f32,
        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
        accepts: impl Fn(NodeId) -> bool,
    ) -> Option<NodeId> {
        self.hit_test_with_plan_and_fg(store, plan, x, y, resolve_transform, |_| false, accepts)
    }

    /// Like [`Self::hit_test_with_plan`], also accepting a predicate reporting backend-specific
    /// Step 7 foreground content (such as registered plugin tables) painted above `NegSc` children.
    #[allow(clippy::too_many_arguments)]
    pub fn hit_test_with_plan_and_fg(
        &self,
        store: &NodeStore,
        plan: &StackingPlan,
        x: f32,
        y: f32,
        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
        has_plugin_fg: impl Fn(NodeId) -> bool,
        accepts: impl Fn(NodeId) -> bool,
    ) -> Option<NodeId> {
        let walk = PlanHitWalk {
            scene: self,
            store,
            plan,
            resolve_transform,
            has_plugin_fg,
        };
        for tl in plan.top_layers.iter().rev() {
            if let Some(hit_box) = walk.walk_scope(tl.scope, (x, y)) {
                return bubble_dom_ancestors(store, hit_box, Some(tl.node_id), &accepts);
            }
            // A modal and a non-modal backdrop scrim both block pointers to everything painted
            // below them. Only a modal makes that content inert (`is_inert_under_modal`: focus,
            // scroll latching, a11y); a scrim'd popover is light-dismissed, never inert.
            if tl.is_modal || tl.backdrop.is_some() {
                return None;
            }
        }
        let root_scope = plan.root?;
        let hit_box = walk.walk_scope(root_scope, (x, y))?;
        bubble_dom_ancestors(store, hit_box, None, &accepts)
    }

    /// Hit-tests `(x, y)` allowing backends to supply an animated `Transform2D` override per node
    /// while reusing the cached zero-alloc [`StackingPlan`] and detecting live `identity <->
    /// non-identity` animated transform transitions even without a store commit.
    pub fn hit_test_where_with_transform(
        &self,
        store: &NodeStore,
        x: f32,
        y: f32,
        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
        accepts: impl Fn(NodeId) -> bool,
    ) -> Option<NodeId> {
        let key = self.stacking_cache_key(store);
        let style = SceneStackingStyleSource::new(self.style_cascade(), &resolve_transform);
        let mut plan = self.stacking_cache.take();
        let needs_rebuild = self.stacking_cache_key.get() != key
            || plan.is_empty()
            || plan.has_transform_mismatch(store, &style);
        if needs_rebuild {
            plan.build(store, self.overlays.open_overlays(), &style);
            self.stacking_cache_key.set(key);
            self.stacking_cache_has_tf_override.set(true);
        }
        let result = self.hit_test_with_plan(store, &plan, x, y, resolve_transform, accepts);
        self.stacking_cache.set(plan);
        result
    }
}