nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Iterative hit-stack, DOM ancestor bubbling, and Step 7 foreground text hit-rect helpers for
//! [`super::hit_test`].

use nativeview_engine::LayoutRect;
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::{Layout as NvLayout, TextAlign, TextContent, Typography, Visual};

use crate::{MAX_TREE_DEPTH, ResolvedTextStyle, TextMeasurer, resolve_inherited_text};

use super::super::stacking::{ClipScrollIdx, ScopeIdx};

const MAX_INLINE_HIT_DEPTH: usize = 64;

#[derive(Clone, Copy)]
pub(crate) struct HitFrame {
    pub(crate) scope_idx: ScopeIdx,
    pub(crate) cursor: u32,
    pub(crate) stop_at: u32,
    pub(crate) entry_clip: ClipScrollIdx,
    pub(crate) entry_offset: (f32, f32),
    pub(crate) scope_point: (f32, f32),
    pub(crate) own_offset: Option<(f32, f32)>,
    pub(crate) depth: u16,
    pub(crate) checked_fg: bool,
}

const EMPTY_HIT_FRAME: HitFrame = HitFrame {
    scope_idx: ScopeIdx::NONE,
    cursor: 0,
    stop_at: 0,
    entry_clip: ClipScrollIdx::NONE,
    entry_offset: (0.0, 0.0),
    scope_point: (0.0, 0.0),
    own_offset: None,
    depth: 0,
    checked_fg: false,
};

pub(crate) struct HitStack {
    inline: [HitFrame; MAX_INLINE_HIT_DEPTH],
    len: usize,
    overflow: Vec<HitFrame>,
}

impl HitStack {
    #[inline]
    pub(crate) fn new() -> Self {
        Self {
            inline: [EMPTY_HIT_FRAME; MAX_INLINE_HIT_DEPTH],
            len: 0,
            overflow: Vec::new(),
        }
    }

    #[inline]
    pub(crate) fn push(&mut self, f: HitFrame) {
        if self.len < MAX_INLINE_HIT_DEPTH {
            self.inline[self.len] = f;
        } else {
            self.overflow.push(f);
        }
        self.len += 1;
    }

    #[inline]
    pub(crate) fn top_mut(&mut self) -> Option<&mut HitFrame> {
        if self.len == 0 {
            None
        } else if self.len <= MAX_INLINE_HIT_DEPTH {
            Some(&mut self.inline[self.len - 1])
        } else {
            self.overflow.last_mut()
        }
    }

    #[inline]
    pub(crate) fn pop(&mut self) -> Option<HitFrame> {
        if self.len == 0 {
            return None;
        }
        self.len -= 1;
        if self.len < MAX_INLINE_HIT_DEPTH {
            Some(self.inline[self.len])
        } else {
            self.overflow.pop()
        }
    }
}

/// Walks DOM ancestors from `hit_box` up to `stop_inclusive` (or `NodeId::ROOT` when `None`),
/// returning the first node accepted by `accepts` (`display: contents` wrappers are included!).
#[inline]
pub(crate) fn bubble_dom_ancestors(
    store: &NodeStore,
    hit_box: NodeId,
    stop_inclusive: Option<NodeId>,
    accepts: &impl Fn(NodeId) -> bool,
) -> Option<NodeId> {
    let mut cur = Some(hit_box);
    for _ in 0..=MAX_TREE_DEPTH {
        let id = cur?;
        if accepts(id) {
            return Some(id);
        }
        if stop_inclusive == Some(id) {
            return None;
        }
        cur = store.parent(id).filter(|&p| p != id);
    }
    None
}

/// Returns `true` when `pt` falls inside the measured Step 7 [`TextContent`] foreground rect of
/// `id` inside its world-space `rect` at `(wx, wy)`. Zero heap allocations.
pub(crate) fn point_in_text_foreground(
    store: &NodeStore,
    measurer: &dyn TextMeasurer,
    id: NodeId,
    wx: f32,
    wy: f32,
    rect: LayoutRect,
    pt: (f32, f32),
) -> bool {
    let Some(text) = store
        .try_row::<TextContent>(id)
        .map(|t| t.text())
        .filter(|t| !t.is_empty())
    else {
        return false;
    };
    let mut chain = [NodeId::NULL; 32];
    let mut len = 0usize;
    let mut cur = Some(id);
    while let Some(n) = cur {
        if len >= chain.len() {
            break;
        }
        chain[len] = n;
        len += 1;
        cur = store.parent(n).filter(|&p| p != n);
    }
    let mut resolved = ResolvedTextStyle::default();
    let mut align = TextAlign::Left;
    for &anc in chain[..len].iter().rev() {
        resolved = resolve_inherited_text(store, anc, resolved);
        if let Some(ty) = store.try_row::<Typography>(anc)
            && ty.is_text_align_explicit()
        {
            align = ty.text_align();
        }
    }
    let (tw, th) = measurer.measure(text, &resolved.in_store(store), Some(rect.width));
    if !(tw > 0.0 && th > 0.0) {
        return false;
    }
    let cw = tw.min(rect.width);
    let ch = th.min(rect.height);
    let tx = match align {
        TextAlign::Center => wx + (rect.width - cw) * 0.5,
        TextAlign::Right => wx + (rect.width - cw),
        _ => wx,
    };
    pt.0 >= tx && pt.0 <= tx + cw && pt.1 >= wy && pt.1 <= wy + ch
}

/// Returns `(left, top, right, bottom)` content insets (`padding + border_width`) of paragraph
/// box `id` at width `box_w`, shared identically across hit-testing, Skia paint, and a11y bounds.
#[inline]
pub fn paragraph_content_insets(store: &NodeStore, id: NodeId, box_w: f32) -> (f32, f32, f32, f32) {
    let bw = store.try_row::<Visual>(id).map_or(0.0, |v| {
        let w = v.border_width();
        if w.is_finite() && w > 0.0 { w } else { 0.0 }
    });
    let (pl, pt, pr, pb) = store
        .try_row::<NvLayout>(id)
        .map_or((0.0, 0.0, 0.0, 0.0), |l| {
            let res = |len: nativeview_store::Length| len.resolve(box_w).unwrap_or(0.0).max(0.0);
            (
                res(l.padding_left()),
                res(l.padding_top()),
                res(l.padding_right()),
                res(l.padding_bottom()),
            )
        });
    (pl + bw, pt + bw, pr + bw, pb + bw)
}

#[cfg(test)]
mod tests {
    use nativeview_abi::InteractionEvent;
    use nativeview_engine::Viewport;
    use nativeview_store::{ChangeSet, Length, NodeId, NodeStore, RowPatch};
    use nativeview_tables::interaction::{FocusModality, InteractionState, StateStyleRule};
    use nativeview_tables::tables::{EventSet, Interaction, Layout, Position, Scroll, StateRules, Visual};

    use crate::{LaidOutScene, TaffyStoreLayout};

    #[test]
    fn scroll_table_clips_hit_tests_without_explicit_visual_overflow() {
        let mut store = NodeStore::new();
        let mut changes = ChangeSet::default();
        let (scroller, child) = {
            let mut tx = store.tx();
            let scroller = tx.create();
            tx.edit::<Layout>(scroller)
                .width(Length::points(120.0))
                .height(Length::points(80.0));
            // Attach `Scroll` with NO `Visual` row — matches Skia's `should_clip_children`.
            tx.edit::<Scroll>(scroller);

            let child = tx.create();
            tx.edit::<Layout>(child)
                .width(Length::points(120.0))
                .height(Length::points(200.0));
            tx.edit::<Interaction>(child)
                .listeners(EventSet::one(InteractionEvent::Press));

            tx.set_children(scroller, &[child]);
            tx.set_children(NodeId::ROOT, &[scroller]);
            tx.commit_into(&mut changes);
            (scroller, child)
        };

        let mut scene = LaidOutScene::new(TaffyStoreLayout::new());
        scene.set_viewport(Viewport {
            width: 400.0,
            height: 400.0,
            scale_factor: 1.0,
        });
        assert!(scene.commit_frame(&store, &changes).layout_ran);

        // Inside the 120x80 scroll viewport hits the interactive child.
        assert_eq!(scene.hit_test(&store, 40.0, 40.0), Some(child));
        // Below the 80px scroll viewport (inside child's 200px overflow) MUST be clipped.
        assert_eq!(scene.hit_test(&store, 40.0, 140.0), None);
        assert_eq!(
            scene.hit_test_scroll_container(&store, 40.0, 40.0),
            Some(scroller)
        );
    }

    #[test]
    fn set_focus_in_store_and_pointer_leave_in_store_invalidate_stacking_cache() {
        let mut store = NodeStore::new();
        let mut changes = ChangeSet::default();
        let (back_box, front_box) = {
            let mut tx = store.tx();
            let back = tx.create();
            let front = tx.create();
            for n in [back, front] {
                tx.edit::<Layout>(n)
                    .position(Position::Absolute)
                    .inset_left(Length::points(0.0))
                    .inset_top(Length::points(0.0))
                    .width(Length::points(100.0))
                    .height(Length::points(100.0));
                tx.edit::<Interaction>(n)
                    .listeners(EventSet::one(InteractionEvent::Press))
                    .focusable(true);
            }
            tx.edit::<Visual>(back).z_index(Some(1));
            tx.edit::<Visual>(front).z_index(Some(2));

            // Focusing or hovering `back` raises its z-index above `front` (z=10 > z=2).
            let mut z_patch = RowPatch::new();
            z_patch.set(Visual::Z_INDEX, Some(10));
            tx.set_resource(
                back,
                Interaction::STATE_RULES,
                Some(&StateRules::new(vec![
                    StateStyleRule::new(InteractionState::FOCUS, z_patch.clone()),
                    StateStyleRule::new(InteractionState::HOVER, z_patch),
                ])),
            );

            tx.set_children(NodeId::ROOT, &[back, front]);
            tx.commit_into(&mut changes);
            (back, front)
        };

        let mut scene = LaidOutScene::new(TaffyStoreLayout::new());
        scene.set_viewport(Viewport {
            width: 200.0,
            height: 200.0,
            scale_factor: 1.0,
        });
        assert!(scene.commit_frame(&store, &changes).layout_ran);

        // Baseline: `front` (z=2) wins over `back` (z=1) and populates `stacking_cache`.
        assert_eq!(scene.hit_test(&store, 50.0, 50.0), Some(front_box));

        // Focus `back` via `set_focus_in_store`: `stacking_cache` MUST invalidate so `back` (z=10) wins!
        let _ = scene.set_focus_in_store(&store, Some(back_box), FocusModality::Keyboard);
        assert_eq!(
            scene.hit_test(&store, 50.0, 50.0),
            Some(back_box),
            "set_focus_in_store must invalidate stacking_cache on :focus z-index change"
        );

        // Hover `back` (now on top) then clear focus via `set_focus_in_store(None)` -> `:hover` keeps `back` on top.
        let _ = scene.pointer_move_in_store(&store, Some(back_box));
        let _ = scene.set_focus_in_store(&store, None, FocusModality::Keyboard);
        assert_eq!(scene.hit_test(&store, 50.0, 50.0), Some(back_box));

        // Leave via `pointer_leave_in_store`: `stacking_cache` MUST invalidate so `front` (z=2) wins again!
        let _ = scene.pointer_leave_in_store(&store);
        assert_eq!(
            scene.hit_test(&store, 50.0, 50.0),
            Some(front_box),
            "pointer_leave_in_store must invalidate stacking_cache on :hover exit"
        );
    }

    #[test]
    fn pointer_events_none_passes_through_and_explicit_auto_child_opts_back_in() {
        use nativeview_tables::tables::PointerEvents;

        let mut store = NodeStore::new();
        let mut changes = ChangeSet::default();
        let (under_btn, overlay_pill, hud_btn) = {
            let mut tx = store.tx();
            let under_btn = tx.create();
            tx.edit::<Layout>(under_btn)
                .position(Position::Absolute)
                .inset_left(Length::points(0.0))
                .inset_top(Length::points(0.0))
                .width(Length::points(120.0))
                .height(Length::points(120.0));
            tx.edit::<Interaction>(under_btn)
                .listeners(EventSet::one(InteractionEvent::Press));

            // Floating z=500 overlay with `PointerEvents::None`, containing a plain label
            // (inherits None) and an explicit `PointerEvents::Auto` HUD button.
            let overlay = tx.create();
            tx.edit::<Layout>(overlay)
                .position(Position::Absolute)
                .inset_left(Length::points(0.0))
                .inset_top(Length::points(0.0))
                .width(Length::points(120.0))
                .height(Length::points(120.0));
            tx.edit::<Visual>(overlay).z_index(Some(500));
            tx.edit::<Interaction>(overlay)
                .pointer_events(Some(PointerEvents::None));

            let overlay_pill = tx.create();
            tx.edit::<Layout>(overlay_pill)
                .position(Position::Absolute)
                .inset_left(Length::points(10.0))
                .inset_top(Length::points(10.0))
                .width(Length::points(50.0))
                .height(Length::points(30.0));

            let hud_btn = tx.create();
            tx.edit::<Layout>(hud_btn)
                .position(Position::Absolute)
                .inset_left(Length::points(70.0))
                .inset_top(Length::points(70.0))
                .width(Length::points(40.0))
                .height(Length::points(40.0));
            tx.edit::<Interaction>(hud_btn)
                .listeners(EventSet::one(InteractionEvent::Press))
                .pointer_events(Some(PointerEvents::Auto));

            tx.set_children(overlay, &[overlay_pill, hud_btn]);
            tx.set_children(NodeId::ROOT, &[under_btn, overlay]);
            tx.commit_into(&mut changes);
            (under_btn, overlay_pill, hud_btn)
        };
        let _ = overlay_pill;

        let mut scene = LaidOutScene::new(TaffyStoreLayout::new());
        scene.set_viewport(Viewport {
            width: 200.0,
            height: 200.0,
            scale_factor: 1.0,
        });
        assert!(scene.commit_frame(&store, &changes).layout_ran);

        // Clicking over the `pointer-events: none` pill passes straight through to `under_btn`.
        assert_eq!(scene.hit_test(&store, 25.0, 20.0), Some(under_btn));
        // Clicking over the explicit `PointerEvents::Auto` child hits `hud_btn`.
        assert_eq!(scene.hit_test(&store, 85.0, 85.0), Some(hud_btn));
    }
}