nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Hover / active / drag-over chain transitions of [`InteractionTracker`] and their dirty sets.

use nativeview_abi::{NodeId, TimestampUs};
use nativeview_tables::interaction::FocusModality;

use super::pointers::{PointerKey, PointerOverflow, PointerSlot};
use super::{InteractionTracker, MAX_CHAIN_DEPTH};

/// What ending a pointer (up or cancel) released.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct PointerEnd {
    /// The ended slot (`None` when the pointer was not active).
    pub slot: Option<PointerSlot>,
    /// Up only: the deepest enabled node in both the primary press chain and the release chain
    /// (the `Press` target).
    pub clicked: Option<NodeId>,
}

impl InteractionTracker {
    pub(super) fn build_chain(&mut self, target: Option<NodeId>, parent_of: impl Fn(NodeId) -> Option<NodeId>) {
        self.next_chain_scratch.clear();
        let Some(mut cur) = target else {
            return;
        };
        for _ in 0..MAX_CHAIN_DEPTH {
            if self.next_chain_scratch.contains(&cur) {
                break;
            }
            self.next_chain_scratch.push(cur);
            match parent_of(cur) {
                Some(p) if p != cur => cur = p,
                _ => break,
            }
        }
    }

    #[inline]
    pub(super) fn push_candidate_id(&mut self, id: NodeId) {
        if !self.candidate_scratch.iter().any(|(existing, _)| *existing == id) {
            let st = self.state(id);
            self.candidate_scratch.push((id, st));
        }
    }

    fn push_candidates_of(&mut self, which: fn(&Self) -> &[NodeId]) {
        for i in 0..which(self).len() {
            let id = which(self)[i];
            self.push_candidate_id(id);
        }
    }

    fn snapshot_pointer_candidates(&mut self) {
        self.candidate_scratch.clear();
        self.push_candidates_of(|t| &t.hovered_chain);
        self.push_candidates_of(|t| &t.active_chain);
        self.push_candidates_of(|t| &t.next_chain_scratch);
    }

    fn diff_hover_enter_exit(&mut self) {
        self.exited_scratch.clear();
        for &id in &self.hovered_chain {
            if !self.next_chain_scratch.contains(&id) {
                self.exited_scratch.push(id);
            }
        }
        self.entered_scratch.clear();
        for &id in self.next_chain_scratch.iter().rev() {
            if !self.hovered_chain.contains(&id) {
                self.entered_scratch.push(id);
            }
        }
    }

    /// Clears enter / exit / dirty for a transition that changed no pseudo-state.
    fn no_transition(&mut self) -> &[NodeId] {
        self.entered_scratch.clear();
        self.exited_scratch.clear();
        self.prev_dirty_scratch.clear();
        &self.prev_dirty_scratch
    }

    pub(super) fn finalize_dirty(&mut self) -> &[NodeId] {
        self.prev_dirty_scratch.clear();
        for i in 0..self.candidate_scratch.len() {
            let (id, prev) = self.candidate_scratch[i];
            if self.state(id) != prev && !self.prev_dirty_scratch.contains(&id) {
                self.prev_dirty_scratch.push(id);
            }
        }
        self.prev_dirty_scratch.sort_unstable();
        &self.prev_dirty_scratch
    }

    /// Moves `key` to `target` (zero-alloc steady state).
    ///
    /// Only the primary hover-capable pointer, while not captured, updates `:hover`
    /// ([`Self::exited`] bottom-up, [`Self::entered`] top-down); when it owns an uncaptured press
    /// it also cancels `:active` on ancestors no longer hovered (press-cancel on drag-off).
    pub fn pointer_move_with(
        &mut self,
        key: PointerKey,
        target: Option<NodeId>,
        parent_of: impl Fn(NodeId) -> Option<NodeId>,
    ) -> &[NodeId] {
        let captured = self.pointers.capture_of(key).is_some();
        if !key.kind.hovers() || captured || !self.pointers.would_be_primary(key) {
            return self.no_transition();
        }
        self.build_chain(target, parent_of);
        self.snapshot_pointer_candidates();
        self.diff_hover_enter_exit();
        core::mem::swap(&mut self.hovered_chain, &mut self.next_chain_scratch);
        if self.active_key == Some(key) && !self.active_press_captured() {
            self.active_chain.retain(|id| self.hovered_chain.contains(id));
        }
        self.finalize_dirty()
    }

    /// Clears hover when the pointer exits the surface/window (zero-alloc steady state).
    ///
    /// Preserves `:active` and every capture while the press owning `:active` is captured, so
    /// captured drags survive `CursorLeft`.
    pub fn pointer_leave_slice(&mut self) -> &[NodeId] {
        self.next_chain_scratch.clear();
        self.snapshot_pointer_candidates();
        self.exited_scratch.clear();
        self.exited_scratch.extend_from_slice(&self.hovered_chain);
        self.entered_scratch.clear();
        self.hovered_chain.clear();
        if !self.active_press_captured() {
            self.active_chain.clear();
            self.active_key = None;
        }
        self.finalize_dirty()
    }

    /// Activates `key` on `target` at `at` (zero-alloc steady state), returning whether it is the
    /// primary pointer. The primary pointer's chain (minus disabled nodes) becomes `:active`;
    /// a hover-capable primary also moves `:hover`. Secondary pointers change no pseudo-state.
    /// A full table refuses the contact.
    pub fn pointer_down_with(
        &mut self,
        key: PointerKey,
        at: [f32; 2],
        ts: TimestampUs,
        target: Option<NodeId>,
        parent_of: impl Fn(NodeId) -> Option<NodeId>,
    ) -> Result<bool, PointerOverflow> {
        self.last_input_modality = FocusModality::Pointer;
        let primary = match self.pointers.begin(key, at, ts, target.unwrap_or(NodeId::NULL)) {
            Ok(slot) => slot.primary,
            Err(e) => {
                let _ = self.no_transition();
                return Err(e);
            }
        };
        if !primary {
            let _ = self.no_transition();
            return Ok(false);
        }
        self.build_chain(target, parent_of);
        self.snapshot_pointer_candidates();
        if key.kind.hovers() {
            self.diff_hover_enter_exit();
            core::mem::swap(&mut self.hovered_chain, &mut self.next_chain_scratch);
        } else {
            // Touch never sets sticky `:hover` (`@media (hover: none)`).
            self.entered_scratch.clear();
            self.exited_scratch.clear();
        }
        let chain = if key.kind.hovers() { &self.hovered_chain } else { &self.next_chain_scratch };
        self.active_chain.clear();
        for &id in chain {
            if !self.disabled.contains(&id) {
                self.active_chain.push(id);
            }
        }
        self.active_key = Some(key);
        let _ = self.finalize_dirty();
        Ok(true)
    }

    /// Ends `key` on release over `target` (zero-alloc steady state), releasing only its own
    /// capture. A primary pointer clears `:active` and reports the click target; a hover-capable
    /// primary moves `:hover` to `target`.
    pub fn pointer_up_with(
        &mut self,
        key: PointerKey,
        target: Option<NodeId>,
        parent_of: impl Fn(NodeId) -> Option<NodeId>,
    ) -> PointerEnd {
        let Some(slot) = self.pointers.end(key) else {
            let _ = self.no_transition();
            return PointerEnd::default();
        };
        if !slot.primary {
            let _ = self.no_transition();
            return PointerEnd { slot: Some(slot), clicked: None };
        }
        self.build_chain(target, parent_of);
        self.snapshot_pointer_candidates();
        let owns_active = self.active_key == Some(key);
        let clicked = owns_active
            .then(|| {
                self.active_chain
                    .iter()
                    .copied()
                    .find(|id| !self.disabled.contains(id) && self.next_chain_scratch.contains(id))
            })
            .flatten();
        if key.kind.hovers() {
            self.diff_hover_enter_exit();
            core::mem::swap(&mut self.hovered_chain, &mut self.next_chain_scratch);
        } else {
            self.entered_scratch.clear();
            self.exited_scratch.clear();
        }
        if owns_active {
            self.active_chain.clear();
            self.active_key = None;
        }
        let _ = self.finalize_dirty();
        PointerEnd { slot: Some(slot), clicked }
    }

    /// Cancels `key` (zero-alloc steady state), releasing only its own capture: a primary pointer
    /// drops `:active`, and a hover-capable primary also drops `:hover`.
    pub fn pointer_cancel(&mut self, key: PointerKey) -> PointerEnd {
        let slot = self.pointers.end(key);
        let primary = slot.map_or(key.kind.hovers() && self.pointers.would_be_primary(key), |s| s.primary);
        if !primary {
            let _ = self.no_transition();
            return PointerEnd { slot, clicked: None };
        }
        self.next_chain_scratch.clear();
        self.snapshot_pointer_candidates();
        self.entered_scratch.clear();
        self.exited_scratch.clear();
        if key.kind.hovers() {
            self.exited_scratch.extend_from_slice(&self.hovered_chain);
            self.hovered_chain.clear();
        }
        if self.active_key == Some(key) {
            self.active_chain.clear();
            self.active_key = None;
        }
        let _ = self.finalize_dirty();
        PointerEnd { slot, clicked: None }
    }

    /// Cancels every pointer interaction (window blur): ends every pointer and clears `:hover`,
    /// `:active` and `:drag-over` (zero-alloc steady state).
    pub fn pointer_cancel_all(&mut self) -> &[NodeId] {
        self.next_chain_scratch.clear();
        self.snapshot_pointer_candidates();
        self.exited_scratch.clear();
        self.exited_scratch.extend_from_slice(&self.hovered_chain);
        self.entered_scratch.clear();
        self.pointers.clear();
        self.hovered_chain.clear();
        self.active_chain.clear();
        self.active_key = None;
        self.drag_exited_scratch.clear();
        self.drag_exited_scratch.extend_from_slice(&self.drag_over_chain);
        self.drag_entered_scratch.clear();
        self.push_candidates_of(|t| &t.drag_over_chain);
        self.drag_over_chain.clear();
        self.finalize_dirty()
    }

    /// Updates `:drag-over` ancestor chain to `target` with zero steady-state heap allocations.
    ///
    /// Populates [`Self::drag_exited`] (bottom-up) and [`Self::drag_entered`] (top-down) so
    /// hosts can emit non-flickering `DragLeave`/`DragEnter` transitions without recomposition.
    pub fn set_drag_over_with(
        &mut self,
        target: Option<NodeId>,
        parent_of: impl Fn(NodeId) -> Option<NodeId>,
    ) -> &[NodeId] {
        self.build_chain(target, parent_of);
        self.candidate_scratch.clear();
        self.push_candidates_of(|t| &t.drag_over_chain);
        self.push_candidates_of(|t| &t.next_chain_scratch);
        self.drag_exited_scratch.clear();
        for &id in &self.drag_over_chain {
            if !self.next_chain_scratch.contains(&id) {
                self.drag_exited_scratch.push(id);
            }
        }
        self.drag_entered_scratch.clear();
        for &id in self.next_chain_scratch.iter().rev() {
            if !self.drag_over_chain.contains(&id) {
                self.drag_entered_scratch.push(id);
            }
        }
        core::mem::swap(&mut self.drag_over_chain, &mut self.next_chain_scratch);
        self.finalize_dirty()
    }

    /// Clears `:drag-over` on every node (zero-alloc steady state).
    pub fn clear_drag_over_slice(&mut self) -> &[NodeId] {
        self.set_drag_over_with(None, |_| None)
    }

    /// Clears `:active` without disturbing hover (a press promoted into a drag, so the release
    /// never synthesizes a stray `Press`).
    pub fn clear_active_slice(&mut self) -> &[NodeId] {
        self.candidate_scratch.clear();
        self.push_candidates_of(|t| &t.active_chain);
        self.active_chain.clear();
        self.active_key = None;
        self.finalize_dirty()
    }
}