Skip to main content

nativeview_layout/scene/hit/
mod.rs

1//! Shared zero-allocation hit-test geometry over [`LaidOutScene`] driven by [`StackingPlan`]:
2//! CSS 2.1 Appendix E reverse stacking walk, top-layer [`Overlay`] modal/scrim hit-blocking,
3//! containing-block overflow clipping & scroll shifts, sticky clamping, `Transform2D` inverse
4//! mapping (with optional animated transform override), `display: contents` flattening, and
5//! DOM ancestor bubbling.
6
7use nativeview_engine::LayoutRect;
8use nativeview_store::{NodeId, NodeStore};
9use nativeview_tables::layout_ext::compute_sticky_offset;
10use nativeview_tables::snapshots::transform_from_patch_view;
11use nativeview_tables::tables::{
12    Interaction, Layout as NvLayout, Overflow, Position, Scroll, Transform as TransformTable,
13    generates_box,
14};
15use nativeview_tables::transform::Transform2D;
16
17use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};
18
19pub(crate) mod helpers;
20mod walk;
21
22use helpers::{bubble_dom_ancestors, paragraph_content_insets};
23use walk::PlanHitWalk;
24use super::stacking::{SceneStackingStyleSource, StackingPlan};
25use super::LaidOutScene;
26
27impl<L: StoreLayoutEngine> LaidOutScene<L> {
28    /// Nearest ancestor of `id` that generates a box (skips `display: contents` ancestors).
29    fn box_parent(store: &NodeStore, id: NodeId) -> Option<NodeId> {
30        let mut cur = store.parent(id);
31        for _ in 0..MAX_TREE_DEPTH {
32            let anc = cur?;
33            if generates_box(store, anc) {
34                return Some(anc);
35            }
36            cur = store.parent(anc);
37        }
38        None
39    }
40
41    /// Computes sticky offset `(dx, dy)` for `id` against its nearest scroll ancestor.
42    pub fn compute_sticky_delta(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
43        if !generates_box(store, id) {
44            return (0.0, 0.0);
45        }
46        self.sticky_delta_of_box(store, id)
47    }
48
49    pub(crate) fn sticky_delta_of_box(&self, store: &NodeStore, id: NodeId) -> (f32, f32) {
50        let Some(l) = store.try_row::<NvLayout>(id) else {
51            return (0.0, 0.0);
52        };
53        // Position and insets through the cascade, in one visit.
54        let (mut position, mut top, mut right, mut bottom, mut left) =
55            (l.position(), l.inset_top(), l.inset_right(), l.inset_bottom(), l.inset_left());
56        self.style_cascade().visit(store, id, |_, pv| {
57            position = pv.get_prop(NvLayout::POSITION).unwrap_or(position);
58            top = pv.get_prop(NvLayout::INSET_TOP).unwrap_or(top);
59            right = pv.get_prop(NvLayout::INSET_RIGHT).unwrap_or(right);
60            bottom = pv.get_prop(NvLayout::INSET_BOTTOM).unwrap_or(bottom);
61            left = pv.get_prop(NvLayout::INSET_LEFT).unwrap_or(left);
62        });
63        if position != Position::Sticky {
64            return (0.0, 0.0);
65        }
66        let Some(node_rect) = self.layout.layout_of(id) else {
67            return (0.0, 0.0);
68        };
69        let Some(parent_id) = Self::box_parent(store, id) else {
70            return (0.0, 0.0);
71        };
72        let Some(cb_rect) = self.layout.layout_of(parent_id) else {
73            return (0.0, 0.0);
74        };
75
76        let mut scroller = parent_id;
77        let mut cur = Some(parent_id);
78        let mut scroll = (0.0f32, 0.0f32);
79        let mut steps = 0usize;
80        while let Some(anc) = cur {
81            if steps > MAX_TREE_DEPTH {
82                break;
83            }
84            steps += 1;
85            let raw = anc;
86            let has_offset = self.scroll.contains(raw);
87            let is_scroll = store.has::<Scroll>(anc) || {
88                let style = self.style_cascade().stacking_style(store, anc);
89                let scrolls = |o: Option<Overflow>| {
90                    matches!(o, Some(Overflow::Scroll | Overflow::Auto))
91                };
92                scrolls(style.overflow_x) || scrolls(style.overflow_y)
93            };
94            if has_offset || is_scroll {
95                scroller = anc;
96                scroll = self.compositor_scroll_offset(raw);
97                break;
98            }
99            cur = Self::box_parent(store, anc);
100        }
101
102        let vp_rect = self.layout.layout_of(scroller).unwrap_or(LayoutRect {
103            x: 0.0,
104            y: 0.0,
105            width: self.viewport.width,
106            height: self.viewport.height,
107        });
108        let insets = nativeview_tables::layout_ext::PositionInsets {
109            top: top.to_dimension(),
110            right: right.to_dimension(),
111            bottom: bottom.to_dimension(),
112            left: left.to_dimension(),
113        };
114        compute_sticky_offset(
115            (node_rect.x, node_rect.y, node_rect.width, node_rect.height),
116            (cb_rect.x, cb_rect.y, cb_rect.width, cb_rect.height),
117            (vp_rect.x, vp_rect.y, vp_rect.width, vp_rect.height),
118            scroll,
119            insets,
120        )
121    }
122
123    /// Reads the `Transform2D` of `id` from `NodeStore`'s `Transform` table (including active
124    /// `StateRules` overrides), if `id` generates a box.
125    pub fn effective_transform(&self, store: &NodeStore, id: NodeId) -> Option<Transform2D> {
126        if !generates_box(store, id) {
127            return None;
128        }
129        let mut base = Self::transform_of_box(store, id);
130        self.visit_effective_patches(store, id, |pv| {
131            if let Some(tf) = transform_from_patch_view(pv) {
132                base = (!tf.is_identity()).then_some(tf);
133            }
134        });
135        base
136    }
137
138    fn transform_of_box(store: &NodeStore, id: NodeId) -> Option<Transform2D> {
139        let t = store.try_row::<TransformTable>(id)?;
140        let tf = Transform2D {
141            translate_x: t.translate_x(),
142            translate_y: t.translate_y(),
143            scale_x: t.scale_x(),
144            scale_y: t.scale_y(),
145            rotate_deg: t.rotate_deg(),
146            origin_x: t.origin_x(),
147            origin_y: t.origin_y(),
148        };
149        (!tf.is_identity()).then_some(tf)
150    }
151
152    /// Returns `true` when `id` subscribes to any UI event via its `Interaction` table.
153    #[inline]
154    pub fn is_event_target(store: &NodeStore, id: NodeId) -> bool {
155        store
156            .try_row::<Interaction>(id)
157            .is_some_and(|i| !i.listeners().is_empty())
158    }
159
160    /// Directly hit-tests local coordinates `(local_x, local_y)` inside paragraph root `para_id`'s
161    /// content box, returning the hit run's leaf `NodeId` (`None` on trailing whitespace / miss).
162    pub fn hit_test_paragraph_leaf(
163        &self,
164        store: &NodeStore,
165        para_id: NodeId,
166        local_x: f32,
167        local_y: f32,
168    ) -> Option<NodeId> {
169        let para = self.paragraphs()?.paragraph_view(store, para_id)?;
170        let rect = self.layout.layout_of(para_id)?;
171        let (cl, _, cr, _) = paragraph_content_insets(store, para_id, rect.width);
172        let content_w = (rect.width - cl - cr).max(0.0);
173        self.text_measurer()
174            .hit_test_paragraph(&para, content_w, local_x, local_y)
175    }
176
177    /// Returns `true` when `id` is a scroll container (it owns a `Scroll` row, which also carries
178    /// its `ScrollEvent` listeners).
179    #[inline]
180    pub fn is_scroll_container(store: &NodeStore, id: NodeId) -> bool {
181        store.has::<Scroll>(id)
182    }
183
184    /// Hit-tests `(x, y)` in reverse CSS 2.1 Appendix E paint order for the deepest node
185    /// subscribing to events.
186    pub fn hit_test(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
187        self.hit_test_where(store, x, y, |id| Self::is_event_target(store, id))
188    }
189
190    /// The deepest painted node at `(x, y)`, unfiltered: the press hit of [`super::top_layer_press`].
191    pub fn hit_test_painted(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
192        self.hit_test_where(store, x, y, |_| true)
193    }
194
195    /// Hit-tests `(x, y)` in reverse CSS 2.1 Appendix E paint order for the deepest scroll
196    /// container (`Scroll` row).
197    pub fn hit_test_scroll_container(
198        &self,
199        store: &NodeStore,
200        x: f32,
201        y: f32,
202    ) -> Option<NodeId> {
203        self.hit_test_where(store, x, y, |id| Self::is_scroll_container(store, id))
204    }
205
206    /// The cache key of the stacking plan for `store`'s current commit, interaction state,
207    /// overlays, and responsive (`@media` / `@container`) resolution.
208    pub(crate) fn stacking_cache_key(&self, store: &NodeStore) -> super::StackingCacheKey {
209        super::StackingCacheKey {
210            store: store.instance_id(),
211            commit_epoch: store.commit_epoch(),
212            interaction_epoch: self.interaction_epoch,
213            overlay_gen: self.overlays.generation(),
214            responsive_epoch: self.layout.responsive_epoch(),
215        }
216    }
217
218    /// Hit-tests `(x, y)` in reverse CSS 2.1 Appendix E paint order for the deepest node
219    /// `accepts` admits (O(1) cached `StackingPlan`, 0 steady-state heap allocations).
220    pub fn hit_test_where(
221        &self,
222        store: &NodeStore,
223        x: f32,
224        y: f32,
225        accepts: impl Fn(NodeId) -> bool,
226    ) -> Option<NodeId> {
227        let key = self.stacking_cache_key(store);
228        let mut plan = self.stacking_cache.take();
229        if self.stacking_cache_has_tf_override.get()
230            || self.stacking_cache_key.get() != key
231            || plan.is_empty()
232        {
233            let style = SceneStackingStyleSource::new(self.style_cascade(), |_, base| base);
234            plan.build(store, self.overlays.open_overlays(), &style);
235            self.stacking_cache_key.set(key);
236            self.stacking_cache_has_tf_override.set(false);
237        }
238        let result = self.hit_test_with_plan(store, &plan, x, y, |_, base| base, accepts);
239        self.stacking_cache.set(plan);
240        result
241    }
242
243    /// Hit-tests `(x, y)` using a caller-supplied pre-built [`StackingPlan`] (such as
244    /// `SkiaBackend`'s retained `CompositorScene::stacking`), guaranteeing exact 1:1 paint/hit
245    /// parity at O(1) zero rebuild cost and 0 heap allocations.
246    pub fn hit_test_with_plan(
247        &self,
248        store: &NodeStore,
249        plan: &StackingPlan,
250        x: f32,
251        y: f32,
252        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
253        accepts: impl Fn(NodeId) -> bool,
254    ) -> Option<NodeId> {
255        self.hit_test_with_plan_and_fg(store, plan, x, y, resolve_transform, |_| false, accepts)
256    }
257
258    /// Like [`Self::hit_test_with_plan`], also accepting a predicate reporting backend-specific
259    /// Step 7 foreground content (such as registered plugin tables) painted above `NegSc` children.
260    #[allow(clippy::too_many_arguments)]
261    pub fn hit_test_with_plan_and_fg(
262        &self,
263        store: &NodeStore,
264        plan: &StackingPlan,
265        x: f32,
266        y: f32,
267        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
268        has_plugin_fg: impl Fn(NodeId) -> bool,
269        accepts: impl Fn(NodeId) -> bool,
270    ) -> Option<NodeId> {
271        let walk = PlanHitWalk {
272            scene: self,
273            store,
274            plan,
275            resolve_transform,
276            has_plugin_fg,
277        };
278        for tl in plan.top_layers.iter().rev() {
279            if let Some(hit_box) = walk.walk_scope(tl.scope, (x, y)) {
280                return bubble_dom_ancestors(store, hit_box, Some(tl.node_id), &accepts);
281            }
282            // A modal and a non-modal backdrop scrim both block pointers to everything painted
283            // below them. Only a modal makes that content inert (`is_inert_under_modal`: focus,
284            // scroll latching, a11y); a scrim'd popover is light-dismissed, never inert.
285            if tl.is_modal || tl.backdrop.is_some() {
286                return None;
287            }
288        }
289        let root_scope = plan.root?;
290        let hit_box = walk.walk_scope(root_scope, (x, y))?;
291        bubble_dom_ancestors(store, hit_box, None, &accepts)
292    }
293
294    /// Hit-tests `(x, y)` allowing backends to supply an animated `Transform2D` override per node
295    /// while reusing the cached zero-alloc [`StackingPlan`] and detecting live `identity <->
296    /// non-identity` animated transform transitions even without a store commit.
297    pub fn hit_test_where_with_transform(
298        &self,
299        store: &NodeStore,
300        x: f32,
301        y: f32,
302        resolve_transform: impl Fn(NodeId, Option<Transform2D>) -> Option<Transform2D>,
303        accepts: impl Fn(NodeId) -> bool,
304    ) -> Option<NodeId> {
305        let key = self.stacking_cache_key(store);
306        let style = SceneStackingStyleSource::new(self.style_cascade(), &resolve_transform);
307        let mut plan = self.stacking_cache.take();
308        let needs_rebuild = self.stacking_cache_key.get() != key
309            || plan.is_empty()
310            || plan.has_transform_mismatch(store, &style);
311        if needs_rebuild {
312            plan.build(store, self.overlays.open_overlays(), &style);
313            self.stacking_cache_key.set(key);
314            self.stacking_cache_has_tf_override.set(true);
315        }
316        let result = self.hit_test_with_plan(store, &plan, x, y, resolve_transform, accepts);
317        self.stacking_cache.set(plan);
318        result
319    }
320}