Skip to main content

nativeview_engine/tracker/
chains.rs

1//! Hover / active / drag-over chain transitions of [`InteractionTracker`] and their dirty sets.
2
3use nativeview_abi::{NodeId, TimestampUs};
4use nativeview_tables::interaction::FocusModality;
5
6use super::pointers::{PointerKey, PointerOverflow, PointerSlot};
7use super::{InteractionTracker, MAX_CHAIN_DEPTH};
8
9/// What ending a pointer (up or cancel) released.
10#[derive(Debug, Clone, Copy, PartialEq, Default)]
11pub struct PointerEnd {
12    /// The ended slot (`None` when the pointer was not active).
13    pub slot: Option<PointerSlot>,
14    /// Up only: the deepest enabled node in both the primary press chain and the release chain
15    /// (the `Press` target).
16    pub clicked: Option<NodeId>,
17}
18
19impl InteractionTracker {
20    pub(super) fn build_chain(&mut self, target: Option<NodeId>, parent_of: impl Fn(NodeId) -> Option<NodeId>) {
21        self.next_chain_scratch.clear();
22        let Some(mut cur) = target else {
23            return;
24        };
25        for _ in 0..MAX_CHAIN_DEPTH {
26            if self.next_chain_scratch.contains(&cur) {
27                break;
28            }
29            self.next_chain_scratch.push(cur);
30            match parent_of(cur) {
31                Some(p) if p != cur => cur = p,
32                _ => break,
33            }
34        }
35    }
36
37    #[inline]
38    pub(super) fn push_candidate_id(&mut self, id: NodeId) {
39        if !self.candidate_scratch.iter().any(|(existing, _)| *existing == id) {
40            let st = self.state(id);
41            self.candidate_scratch.push((id, st));
42        }
43    }
44
45    fn push_candidates_of(&mut self, which: fn(&Self) -> &[NodeId]) {
46        for i in 0..which(self).len() {
47            let id = which(self)[i];
48            self.push_candidate_id(id);
49        }
50    }
51
52    fn snapshot_pointer_candidates(&mut self) {
53        self.candidate_scratch.clear();
54        self.push_candidates_of(|t| &t.hovered_chain);
55        self.push_candidates_of(|t| &t.active_chain);
56        self.push_candidates_of(|t| &t.next_chain_scratch);
57    }
58
59    fn diff_hover_enter_exit(&mut self) {
60        self.exited_scratch.clear();
61        for &id in &self.hovered_chain {
62            if !self.next_chain_scratch.contains(&id) {
63                self.exited_scratch.push(id);
64            }
65        }
66        self.entered_scratch.clear();
67        for &id in self.next_chain_scratch.iter().rev() {
68            if !self.hovered_chain.contains(&id) {
69                self.entered_scratch.push(id);
70            }
71        }
72    }
73
74    /// Clears enter / exit / dirty for a transition that changed no pseudo-state.
75    fn no_transition(&mut self) -> &[NodeId] {
76        self.entered_scratch.clear();
77        self.exited_scratch.clear();
78        self.prev_dirty_scratch.clear();
79        &self.prev_dirty_scratch
80    }
81
82    pub(super) fn finalize_dirty(&mut self) -> &[NodeId] {
83        self.prev_dirty_scratch.clear();
84        for i in 0..self.candidate_scratch.len() {
85            let (id, prev) = self.candidate_scratch[i];
86            if self.state(id) != prev && !self.prev_dirty_scratch.contains(&id) {
87                self.prev_dirty_scratch.push(id);
88            }
89        }
90        self.prev_dirty_scratch.sort_unstable();
91        &self.prev_dirty_scratch
92    }
93
94    /// Moves `key` to `target` (zero-alloc steady state).
95    ///
96    /// Only the primary hover-capable pointer, while not captured, updates `:hover`
97    /// ([`Self::exited`] bottom-up, [`Self::entered`] top-down); when it owns an uncaptured press
98    /// it also cancels `:active` on ancestors no longer hovered (press-cancel on drag-off).
99    pub fn pointer_move_with(
100        &mut self,
101        key: PointerKey,
102        target: Option<NodeId>,
103        parent_of: impl Fn(NodeId) -> Option<NodeId>,
104    ) -> &[NodeId] {
105        let captured = self.pointers.capture_of(key).is_some();
106        if !key.kind.hovers() || captured || !self.pointers.would_be_primary(key) {
107            return self.no_transition();
108        }
109        self.build_chain(target, parent_of);
110        self.snapshot_pointer_candidates();
111        self.diff_hover_enter_exit();
112        core::mem::swap(&mut self.hovered_chain, &mut self.next_chain_scratch);
113        if self.active_key == Some(key) && !self.active_press_captured() {
114            self.active_chain.retain(|id| self.hovered_chain.contains(id));
115        }
116        self.finalize_dirty()
117    }
118
119    /// Clears hover when the pointer exits the surface/window (zero-alloc steady state).
120    ///
121    /// Preserves `:active` and every capture while the press owning `:active` is captured, so
122    /// captured drags survive `CursorLeft`.
123    pub fn pointer_leave_slice(&mut self) -> &[NodeId] {
124        self.next_chain_scratch.clear();
125        self.snapshot_pointer_candidates();
126        self.exited_scratch.clear();
127        self.exited_scratch.extend_from_slice(&self.hovered_chain);
128        self.entered_scratch.clear();
129        self.hovered_chain.clear();
130        if !self.active_press_captured() {
131            self.active_chain.clear();
132            self.active_key = None;
133        }
134        self.finalize_dirty()
135    }
136
137    /// Activates `key` on `target` at `at` (zero-alloc steady state), returning whether it is the
138    /// primary pointer. The primary pointer's chain (minus disabled nodes) becomes `:active`;
139    /// a hover-capable primary also moves `:hover`. Secondary pointers change no pseudo-state.
140    /// A full table refuses the contact.
141    pub fn pointer_down_with(
142        &mut self,
143        key: PointerKey,
144        at: [f32; 2],
145        ts: TimestampUs,
146        target: Option<NodeId>,
147        parent_of: impl Fn(NodeId) -> Option<NodeId>,
148    ) -> Result<bool, PointerOverflow> {
149        self.last_input_modality = FocusModality::Pointer;
150        let primary = match self.pointers.begin(key, at, ts, target.unwrap_or(NodeId::NULL)) {
151            Ok(slot) => slot.primary,
152            Err(e) => {
153                let _ = self.no_transition();
154                return Err(e);
155            }
156        };
157        if !primary {
158            let _ = self.no_transition();
159            return Ok(false);
160        }
161        self.build_chain(target, parent_of);
162        self.snapshot_pointer_candidates();
163        if key.kind.hovers() {
164            self.diff_hover_enter_exit();
165            core::mem::swap(&mut self.hovered_chain, &mut self.next_chain_scratch);
166        } else {
167            // Touch never sets sticky `:hover` (`@media (hover: none)`).
168            self.entered_scratch.clear();
169            self.exited_scratch.clear();
170        }
171        let chain = if key.kind.hovers() { &self.hovered_chain } else { &self.next_chain_scratch };
172        self.active_chain.clear();
173        for &id in chain {
174            if !self.disabled.contains(&id) {
175                self.active_chain.push(id);
176            }
177        }
178        self.active_key = Some(key);
179        let _ = self.finalize_dirty();
180        Ok(true)
181    }
182
183    /// Ends `key` on release over `target` (zero-alloc steady state), releasing only its own
184    /// capture. A primary pointer clears `:active` and reports the click target; a hover-capable
185    /// primary moves `:hover` to `target`.
186    pub fn pointer_up_with(
187        &mut self,
188        key: PointerKey,
189        target: Option<NodeId>,
190        parent_of: impl Fn(NodeId) -> Option<NodeId>,
191    ) -> PointerEnd {
192        let Some(slot) = self.pointers.end(key) else {
193            let _ = self.no_transition();
194            return PointerEnd::default();
195        };
196        if !slot.primary {
197            let _ = self.no_transition();
198            return PointerEnd { slot: Some(slot), clicked: None };
199        }
200        self.build_chain(target, parent_of);
201        self.snapshot_pointer_candidates();
202        let owns_active = self.active_key == Some(key);
203        let clicked = owns_active
204            .then(|| {
205                self.active_chain
206                    .iter()
207                    .copied()
208                    .find(|id| !self.disabled.contains(id) && self.next_chain_scratch.contains(id))
209            })
210            .flatten();
211        if key.kind.hovers() {
212            self.diff_hover_enter_exit();
213            core::mem::swap(&mut self.hovered_chain, &mut self.next_chain_scratch);
214        } else {
215            self.entered_scratch.clear();
216            self.exited_scratch.clear();
217        }
218        if owns_active {
219            self.active_chain.clear();
220            self.active_key = None;
221        }
222        let _ = self.finalize_dirty();
223        PointerEnd { slot: Some(slot), clicked }
224    }
225
226    /// Cancels `key` (zero-alloc steady state), releasing only its own capture: a primary pointer
227    /// drops `:active`, and a hover-capable primary also drops `:hover`.
228    pub fn pointer_cancel(&mut self, key: PointerKey) -> PointerEnd {
229        let slot = self.pointers.end(key);
230        let primary = slot.map_or(key.kind.hovers() && self.pointers.would_be_primary(key), |s| s.primary);
231        if !primary {
232            let _ = self.no_transition();
233            return PointerEnd { slot, clicked: None };
234        }
235        self.next_chain_scratch.clear();
236        self.snapshot_pointer_candidates();
237        self.entered_scratch.clear();
238        self.exited_scratch.clear();
239        if key.kind.hovers() {
240            self.exited_scratch.extend_from_slice(&self.hovered_chain);
241            self.hovered_chain.clear();
242        }
243        if self.active_key == Some(key) {
244            self.active_chain.clear();
245            self.active_key = None;
246        }
247        let _ = self.finalize_dirty();
248        PointerEnd { slot, clicked: None }
249    }
250
251    /// Cancels every pointer interaction (window blur): ends every pointer and clears `:hover`,
252    /// `:active` and `:drag-over` (zero-alloc steady state).
253    pub fn pointer_cancel_all(&mut self) -> &[NodeId] {
254        self.next_chain_scratch.clear();
255        self.snapshot_pointer_candidates();
256        self.exited_scratch.clear();
257        self.exited_scratch.extend_from_slice(&self.hovered_chain);
258        self.entered_scratch.clear();
259        self.pointers.clear();
260        self.hovered_chain.clear();
261        self.active_chain.clear();
262        self.active_key = None;
263        self.drag_exited_scratch.clear();
264        self.drag_exited_scratch.extend_from_slice(&self.drag_over_chain);
265        self.drag_entered_scratch.clear();
266        self.push_candidates_of(|t| &t.drag_over_chain);
267        self.drag_over_chain.clear();
268        self.finalize_dirty()
269    }
270
271    /// Updates `:drag-over` ancestor chain to `target` with zero steady-state heap allocations.
272    ///
273    /// Populates [`Self::drag_exited`] (bottom-up) and [`Self::drag_entered`] (top-down) so
274    /// hosts can emit non-flickering `DragLeave`/`DragEnter` transitions without recomposition.
275    pub fn set_drag_over_with(
276        &mut self,
277        target: Option<NodeId>,
278        parent_of: impl Fn(NodeId) -> Option<NodeId>,
279    ) -> &[NodeId] {
280        self.build_chain(target, parent_of);
281        self.candidate_scratch.clear();
282        self.push_candidates_of(|t| &t.drag_over_chain);
283        self.push_candidates_of(|t| &t.next_chain_scratch);
284        self.drag_exited_scratch.clear();
285        for &id in &self.drag_over_chain {
286            if !self.next_chain_scratch.contains(&id) {
287                self.drag_exited_scratch.push(id);
288            }
289        }
290        self.drag_entered_scratch.clear();
291        for &id in self.next_chain_scratch.iter().rev() {
292            if !self.drag_over_chain.contains(&id) {
293                self.drag_entered_scratch.push(id);
294            }
295        }
296        core::mem::swap(&mut self.drag_over_chain, &mut self.next_chain_scratch);
297        self.finalize_dirty()
298    }
299
300    /// Clears `:drag-over` on every node (zero-alloc steady state).
301    pub fn clear_drag_over_slice(&mut self) -> &[NodeId] {
302        self.set_drag_over_with(None, |_| None)
303    }
304
305    /// Clears `:active` without disturbing hover (a press promoted into a drag, so the release
306    /// never synthesizes a stray `Press`).
307    pub fn clear_active_slice(&mut self) -> &[NodeId] {
308        self.candidate_scratch.clear();
309        self.push_candidates_of(|t| &t.active_chain);
310        self.active_chain.clear();
311        self.active_key = None;
312        self.finalize_dirty()
313    }
314}