Skip to main content

nativeview_layout/scene/
interaction.rs

1//! Interactive pseudo-state tracking (`:hover`, `:focus`, `:focus-visible`, `:active`,
2//! `:disabled`), pointer capture, and ancestor-inheriting [`CursorKind`] resolution shared across
3//! [`LaidOutScene`] consumers.
4
5use nativeview_abi::TimestampUs;
6use nativeview_engine::InteractionTracker;
7use nativeview_engine::tracker::PointerKey;
8use nativeview_store::{NodeId, NodeStore, ResolvedRow, ResourceId, Rgba, RowPatchView};
9use nativeview_tables::interaction::{
10    CursorKind, FocusModality, InteractionState,
11};
12use nativeview_tables::snapshots::{
13    LayoutSnapshot, VisualSnapshot, apply_patch_view_to_layout, apply_patch_view_to_visual,
14};
15use nativeview_tables::tables::{
16    DragDrop, Interaction, PointerCaptureMode, TextAlign, Typography, Visual, paint_of_box,
17};
18
19use crate::{MAX_TREE_DEPTH, StoreLayoutEngine};
20
21use super::style_cascade::StyleCascade;
22use super::{LaidOutScene, layout_snapshot_of, visual_snapshot_of};
23
24/// One pseudo-state change (`*_in_store`): the nodes whose pseudo-state changed, and whether it
25/// re-ran layout (paragraph `StateRules`, `StateRules` box patches, top-layer re-hoisting).
26/// Retained hosts must sync layout changes (`changed_rects()` / incremental layout delta or full
27/// scene resync) when `relayout` is set; otherwise repainting `dirty` suffices.
28#[must_use]
29#[derive(Debug, Clone, Copy)]
30pub struct InteractionChange<'a> {
31    pub dirty: &'a [NodeId],
32    pub relayout: bool,
33}
34
35impl<L: StoreLayoutEngine> LaidOutScene<L> {
36    /// Feeds the tracker's last pseudo-state change to the engine (paragraph `StateRules`,
37    /// `StateRules` `display` / `position` reflow, top-layer re-hoisting) and runs the engine's
38    /// self-gated layout pass plus an overlay reconcile when anything was invalidated. Returns
39    /// whether layout ran.
40    pub(crate) fn sync_interaction_dirty(&mut self, store: &NodeStore) -> bool {
41        let dirty = self.interaction.last_dirty();
42        if dirty.is_empty() {
43            return false;
44        }
45        let _ = self
46            .layout
47            .sync_interaction_paragraphs(store, &self.interaction, dirty);
48        let relayout = self.recompute_layout(store);
49        if relayout {
50            self.reconcile_overlays_with_transform(store, |_, base| base);
51        }
52        relayout
53    }
54
55    /// Wraps the tracker's last change with whether it re-ran layout.
56    #[inline]
57    fn interaction_change(&mut self, store: &NodeStore) -> InteractionChange<'_> {
58        let relayout = self.sync_interaction_dirty(store);
59        InteractionChange {
60            dirty: self.interaction.last_dirty(),
61            relayout,
62        }
63    }
64
65    #[inline]
66    pub fn interaction_tracker(&self) -> &InteractionTracker {
67        &self.interaction
68    }
69
70    /// Bumped on every pseudo-state change (pointer, focus, disabled, capture): state-rule
71    /// results may differ since a caller last saw another value.
72    #[inline]
73    pub fn interaction_epoch(&self) -> u64 {
74        self.interaction_epoch
75    }
76
77    /// The engine's [`StoreLayoutEngine::responsive_epoch`]: `@media` / `@container` results may
78    /// differ since a caller last saw another value.
79    #[inline]
80    pub fn responsive_epoch(&self) -> u64 {
81        self.layout.responsive_epoch()
82    }
83
84    #[inline]
85    pub(crate) fn bump_interaction_epoch(&mut self) {
86        self.interaction_epoch = self.interaction_epoch.wrapping_add(1).max(1);
87    }
88
89    #[inline]
90    pub fn interaction_tracker_mut(&mut self) -> &mut InteractionTracker {
91        self.bump_interaction_epoch();
92        &mut self.interaction
93    }
94
95    #[inline]
96    pub fn interaction_state(&self, node_id: NodeId) -> InteractionState {
97        self.interaction.state(node_id)
98    }
99
100    /// Returns `true` when `id` or any ancestor up to root is disabled (via `Interaction::disabled`
101    /// or [`InteractionTracker::is_disabled`]).
102    #[inline]
103    pub fn is_subtree_disabled(&self, store: &NodeStore, id: NodeId) -> bool {
104        let mut cur = Some(id);
105        for _ in 0..MAX_TREE_DEPTH {
106            let Some(nid) = cur else {
107                break;
108            };
109            if self.interaction.is_disabled(nid)
110                || store
111                    .try_row::<Interaction>(nid)
112                    .is_some_and(|i| i.disabled())
113            {
114                return true;
115            }
116            cur = store.parent(nid).filter(|&p| p != nid);
117        }
118        false
119    }
120
121    /// Marks `id` disabled or enabled in the [`InteractionTracker`] (dropping `:active`, focus
122    /// and every pointer capture on it), returning the dirty `NodeId`s.
123    pub fn set_node_disabled(&mut self, id: NodeId, disabled: bool) -> &[NodeId] {
124        self.bump_interaction_epoch();
125        self.interaction.set_disabled_slice(id, disabled)
126    }
127
128    /// Returns `true` when `id` participates in pointer hover/active/cursor hit-testing.
129    #[inline]
130    pub fn is_interaction_target(&self, store: &NodeStore, id: NodeId) -> bool {
131        if !self.is_displayed(store, id) {
132            return false;
133        }
134        let has_inter = store.try_row::<Interaction>(id).is_some_and(|i| {
135            !i.listeners().is_empty()
136                || i.cursor() != CursorKind::Auto
137                || i.disabled()
138                || i.focusable()
139                || i.capture_mode() != PointerCaptureMode::None
140                || !i.state_rules().is_none()
141                || i.captures_text_keys()
142                || i.tab_index().is_some()
143        });
144        let has_drag = store.try_row::<DragDrop>(id).is_some_and(|d| {
145            d.draggable() || !d.accept().is_empty() || !d.listeners().is_empty()
146        });
147        has_inter
148            || has_drag
149            || self.interaction.is_disabled(id)
150    }
151
152    /// Returns `true` when `id` is an active drop target (`DragDrop::accept != EMPTY`).
153    #[inline]
154    pub fn is_drop_target(store: &NodeStore, id: NodeId) -> bool {
155        // Visibility is decided by the cascaded stacking plan the hit test walks.
156        store.is_live(id)
157            && store.try_row::<DragDrop>(id).is_some_and(|d| !d.accept().is_empty())
158    }
159
160    /// Returns `true` when `id` is a live visible draggable source (`DragDrop::draggable == true`).
161    #[inline]
162    pub fn is_draggable_target(store: &NodeStore, id: NodeId) -> bool {
163        // Visibility is decided by the cascaded stacking plan the hit test walks.
164        store.is_live(id)
165            && store.try_row::<DragDrop>(id).is_some_and(|d| d.draggable())
166    }
167
168    /// Hit-tests `(x, y)` in reverse paint order for the deepest interaction-eligible node.
169    pub fn hit_test_interaction(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
170        self.hit_test_where(store, x, y, |id| self.is_interaction_target(store, id))
171    }
172
173    /// Hit-tests `(x, y)` in reverse paint order for the deepest drop-zone target.
174    pub fn hit_test_drop_zone(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
175        self.hit_test_where(store, x, y, |id| Self::is_drop_target(store, id))
176    }
177
178    /// Hit-tests `(x, y)` in reverse paint order for the deepest draggable source node.
179    pub fn hit_test_draggable(&self, store: &NodeStore, x: f32, y: f32) -> Option<NodeId> {
180        self.hit_test_where(store, x, y, |id| Self::is_draggable_target(store, id))
181    }
182
183    /// Visits every [`RowPatchView`] overriding `id`'s base style in cascade order: matching
184    /// `@media`, then `@container` rules (committed layout env), then state rules matching its
185    /// current [`InteractionState`] (zero allocations up to 16 rules).
186    pub fn visit_effective_patches<'a>(
187        &self,
188        store: &'a NodeStore,
189        id: NodeId,
190        mut f: impl FnMut(RowPatchView<'a>),
191    ) {
192        self.style_cascade().visit(store, id, |_, pv| f(pv));
193    }
194
195    /// Whether `id` is live and its cascaded `display` is not `none`.
196    #[inline]
197    pub fn is_displayed(&self, store: &NodeStore, id: NodeId) -> bool {
198        store.is_live(id) && !self.style_cascade().effective_box(store, id).is_none()
199    }
200
201    /// The scene's single `base -> @media -> @container -> state` style cascade.
202    #[inline]
203    pub fn style_cascade(&self) -> StyleCascade<'_, L> {
204        StyleCascade {
205            responsive: &self.layout,
206            interaction: Some(&self.interaction),
207            inert: Some(&self.overlays),
208        }
209    }
210
211    /// Resolves the effective [`VisualSnapshot`] for `id` with responsive and pseudo-state rules
212    /// applied.
213    pub fn effective_visual(&self, store: &NodeStore, id: NodeId) -> VisualSnapshot {
214        let mut visual = visual_snapshot_of(store, id);
215        self.visit_effective_patches(store, id, |pv| apply_patch_view_to_visual(pv, &mut visual));
216        paint_of_box(store, id, visual)
217    }
218
219    /// Resolves both [`LayoutSnapshot`] and [`VisualSnapshot`] for `id` with responsive and
220    /// pseudo-state rules applied.
221    pub fn effective_layout_and_visual(
222        &self,
223        store: &NodeStore,
224        id: NodeId,
225    ) -> (LayoutSnapshot, VisualSnapshot) {
226        let mut layout = layout_snapshot_of(store, id);
227        let mut visual = visual_snapshot_of(store, id);
228        self.visit_effective_patches(store, id, |pv| {
229            apply_patch_view_to_layout(pv, &mut layout);
230            apply_patch_view_to_visual(pv, &mut visual);
231        });
232        (layout, paint_of_box(store, id, visual))
233    }
234
235    /// Resolves the effective `BackgroundFillRes` resource id for `id`, respecting responsive and
236    /// state-rule patches (including solid `background` overrides clearing a base gradient).
237    #[inline]
238    pub fn effective_background_fill_res(&self, store: &NodeStore, id: NodeId) -> Option<ResourceId> {
239        let mut patched: Option<ResourceId> = None;
240        self.visit_effective_patches(store, id, |pv| {
241            if let Some(rid) = pv.get_res_id(Visual::BACKGROUND_FILL) {
242                patched = Some(rid);
243            } else if pv.get_prop(Visual::BACKGROUND).is_some() {
244                patched = Some(ResourceId::NONE);
245            }
246        });
247        match patched {
248            Some(rid) => (!rid.is_none()).then_some(rid),
249            None => store
250                .try_row::<Visual>(id)
251                .map(|v| v.background_fill())
252                .filter(|rid| !rid.is_none()),
253        }
254    }
255
256    /// Resolves inherited `(font_weight, text_align, text_color, font_size)` for `id` using
257    /// branchless `ResolvedRow<Typography>` over `parent_text`, layered with responsive/state
258    /// patches and an optional animated text color override.
259    #[inline]
260    pub fn resolve_text_style_fields(
261        &self,
262        store: &NodeStore,
263        id: NodeId,
264        style: &VisualSnapshot,
265        parent_text: Option<(u16, TextAlign, Rgba, f32)>,
266        color_hooked: bool,
267    ) -> (u16, TextAlign, Rgba, f32) {
268        let mut parent_row = ResolvedRow::<Typography>::root(store);
269        if let Some((w, align, color, size)) = parent_text {
270            parent_row.override_prop(Typography::COLOR, color);
271            parent_row.override_prop(Typography::FONT_SIZE, size);
272            parent_row.override_prop(Typography::FONT_WEIGHT, w);
273            parent_row.override_prop(Typography::TEXT_ALIGN, align);
274        }
275        let resolved_typo = ResolvedRow::<Typography>::resolve(store, id, &parent_row);
276        let typo = resolved_typo.get();
277        let (mut color_ov, mut size_ov, mut weight_ov, mut align_ov) =
278            (color_hooked, false, None, None);
279        self.visit_effective_patches(store, id, |pv| {
280            if pv.get_prop(Typography::COLOR).is_some() {
281                color_ov = true;
282            }
283            if pv.get_prop(Typography::FONT_SIZE).is_some() {
284                size_ov = true;
285            }
286            if let Some(w) = pv.get_prop(Typography::FONT_WEIGHT) {
287                weight_ov = Some(w);
288            }
289            if let Some(a) = pv.get_prop(Typography::TEXT_ALIGN) {
290                align_ov = Some(a);
291            }
292        });
293        (
294            weight_ov.unwrap_or_else(|| typo.font_weight()),
295            align_ov.unwrap_or_else(|| typo.text_align()),
296            if color_ov { Rgba::from(style.text_color) } else { typo.color() },
297            if size_ov { style.font_size } else { typo.font_size() },
298        )
299    }
300
301    fn local_cursor_of(&self, store: &NodeStore, id: NodeId) -> CursorKind {
302        let inter = store.try_row::<Interaction>(id);
303        let base_cursor = inter.map(|i| i.cursor()).unwrap_or(CursorKind::Auto);
304        let captures_text = inter.is_some_and(|i| i.captures_text_keys());
305        let base = if base_cursor == CursorKind::Auto && captures_text {
306            CursorKind::Text
307        } else {
308            base_cursor
309        };
310        self.style_cascade()
311            .patched(store, id, Interaction::CURSOR)
312            .unwrap_or(base)
313    }
314
315    /// Resolves the effective [`CursorKind`] for `id` in a single `O(depth)` leaf-to-root walk,
316    /// converting `Pointer` to `NotAllowed` whenever `id` or any ancestor is disabled.
317    pub fn effective_cursor(&self, store: &NodeStore, id: NodeId) -> CursorKind {
318        if !self.is_displayed(store, id) {
319            return CursorKind::Auto;
320        }
321        let mut cur = Some(id);
322        let mut found: Option<CursorKind> = None;
323        let mut disabled_seen = false;
324        for _ in 0..MAX_TREE_DEPTH {
325            let Some(nid) = cur else {
326                break;
327            };
328            if self.interaction.is_disabled(nid)
329                || store.try_row::<Interaction>(nid).is_some_and(|i| i.disabled())
330            {
331                disabled_seen = true;
332                if found == Some(CursorKind::Pointer) {
333                    return CursorKind::NotAllowed;
334                }
335            }
336            if found.is_none() {
337                let resolved = self.local_cursor_of(store, nid);
338                if resolved != CursorKind::Auto {
339                    if resolved != CursorKind::Pointer {
340                        return resolved;
341                    }
342                    if disabled_seen {
343                        return CursorKind::NotAllowed;
344                    }
345                    found = Some(resolved);
346                }
347            }
348            cur = store.parent(nid).filter(|&p| p != nid);
349        }
350        found.unwrap_or(CursorKind::Auto)
351    }
352
353    /// Resolves the active cursor in `O(depth)`: checks captured node first, then the deepest
354    /// live hovered node, then the deepest live active node, falling back to `CursorKind::Default`.
355    pub fn current_cursor(&self, store: &NodeStore) -> CursorKind {
356        if let Some(cap) = self.interaction.captured_node() {
357            let c = self.effective_cursor(store, cap);
358            return if c == CursorKind::Auto {
359                CursorKind::Default
360            } else {
361                c
362            };
363        }
364        if let Some(&leaf) = self
365            .interaction
366            .hovered_chain()
367            .iter()
368            .find(|&&id| self.is_displayed(store, id))
369        {
370            let c = self.effective_cursor(store, leaf);
371            if c != CursorKind::Auto {
372                return c;
373            }
374        }
375        if let Some(&leaf) = self
376            .interaction
377            .active_chain()
378            .iter()
379            .find(|&&id| self.is_displayed(store, id))
380        {
381            let c = self.effective_cursor(store, leaf);
382            if c != CursorKind::Auto {
383                return c;
384            }
385        }
386        CursorKind::Default
387    }
388
389    /// Moves the mouse ([`PointerKey::MOUSE`]) to `target` directly, bypassing hit testing and
390    /// event synthesis (pseudo-state drivers: benches, inspectors). Hosts route samples through
391    /// [`Self::resolve_pointer`].
392    #[inline]
393    pub fn pointer_move_in_store(
394        &mut self,
395        store: &NodeStore,
396        target: Option<NodeId>,
397    ) -> InteractionChange<'_> {
398        self.bump_interaction_epoch();
399        let _ = self
400            .interaction
401            .pointer_move_with(PointerKey::MOUSE, target, |id| store.parent(id));
402        self.interaction_change(store)
403    }
404
405    /// Presses the mouse's primary button on `target` directly (see [`Self::pointer_move_in_store`]).
406    #[inline]
407    pub fn pointer_down_in_store(
408        &mut self,
409        store: &NodeStore,
410        target: Option<NodeId>,
411    ) -> InteractionChange<'_> {
412        self.bump_interaction_epoch();
413        let _ = self.interaction.pointer_down_with(
414            PointerKey::MOUSE,
415            [0.0, 0.0],
416            TimestampUs::ZERO,
417            target,
418            |id| store.parent(id),
419        );
420        self.interaction_change(store)
421    }
422
423    /// Releases the mouse over `target` directly, returning `(clicked_node, change)` (see
424    /// [`Self::pointer_move_in_store`]).
425    #[inline]
426    pub fn pointer_up_in_store(
427        &mut self,
428        store: &NodeStore,
429        target: Option<NodeId>,
430    ) -> (Option<NodeId>, InteractionChange<'_>) {
431        self.bump_interaction_epoch();
432        let end = self
433            .interaction
434            .pointer_up_with(PointerKey::MOUSE, target, |id| store.parent(id));
435        (end.clicked, self.interaction_change(store))
436    }
437
438    /// The pointer left the surface: clears `:hover` (an uncaptured press also drops `:active`).
439    #[inline]
440    pub fn pointer_leave_in_store(&mut self, store: &NodeStore) -> InteractionChange<'_> {
441        self.bump_interaction_epoch();
442        let _ = self.interaction.pointer_leave_slice();
443        self.interaction_change(store)
444    }
445
446    /// Cancels every pointer (window blur): ends every pointer and its capture and clears
447    /// `:hover`, `:active` and `:drag-over`.
448    #[inline]
449    pub fn pointer_cancel_in_store(&mut self, store: &NodeStore) -> InteractionChange<'_> {
450        self.bump_interaction_epoch();
451        let _ = self.interaction.pointer_cancel_all();
452        self.interaction_change(store)
453    }
454
455    /// Zero-alloc `:drag-over` ancestor-chain update against `store`, syncing inline paragraphs.
456    #[inline]
457    pub fn set_drag_over_in_store(
458        &mut self,
459        store: &NodeStore,
460        target: Option<NodeId>,
461    ) -> InteractionChange<'_> {
462        self.bump_interaction_epoch();
463        let _ = self
464            .interaction
465            .set_drag_over_with(target, |id| store.parent(id));
466        self.interaction_change(store)
467    }
468
469    /// Zero-alloc `:active` press clear against `store` (used on drag activation).
470    #[inline]
471    pub fn clear_active_in_store(&mut self, store: &NodeStore) -> InteractionChange<'_> {
472        self.bump_interaction_epoch();
473        let _ = self.interaction.clear_active_slice();
474        self.interaction_change(store)
475    }
476
477    /// Zero-alloc focus update against `store`, syncing any affected inline paragraphs and
478    /// capturing the focus anchor for deterministic post-commit unmount recovery.
479    #[inline]
480    pub fn set_focus_in_store(
481        &mut self,
482        store: &NodeStore,
483        node_id: Option<NodeId>,
484        modality: FocusModality,
485    ) -> InteractionChange<'_> {
486        self.last_focus_transition = None;
487        self.bump_interaction_epoch();
488        let is_text = node_id.is_some_and(|id| nativeview_engine::is_text_entry_node(store, id));
489        let _ = self.interaction.set_focus_ex(node_id, modality, is_text);
490        if self.interaction.focused() == node_id {
491            let mut anchor = core::mem::take(self.interaction.focus_anchor_mut());
492            nativeview_engine::snapshot_focus_anchor(
493                store,
494                &super::cascade_of(&self.layout, &self.interaction),
495                &mut anchor,
496                node_id,
497                modality,
498                &mut self.focus_dfs_scratch,
499            );
500            *self.interaction.focus_anchor_mut() = anchor;
501        }
502        self.interaction_change(store)
503    }
504}