nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
//! Pluggable per-surface scroll physics engine trait ([`ScrollPhysicsEngine`]), zero-cost default
//! ([`InstantScrollPhysics`]), input modality types, and cross-platform `Shift+Wheel`
//! normalization.
//!
//! [`LaidOutScene`](crate::LaidOutScene) defaults to [`InstantScrollPhysics`] (0 B state, 0 CPU
//! overhead) so `nativeview-runtime`, `HeadlessBackend`, and OS-native widget hosts pay nothing for
//! synthetic scroll physics. Custom-drawn hosts (e.g. `hosts/skia-shell`) install a full physics
//! engine such as `nativeview-scroll-physics` via
//! [`LaidOutScene::set_scroll_physics`](crate::LaidOutScene::set_scroll_physics).

use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::tables::OverscrollBehavior;

use super::ScrollOffsets;

/// Monotonic millisecond timestamp for scroll gesture velocity tracking and latch expiry.
#[repr(transparent)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ScrollTimestampMs(pub u64);

impl ScrollTimestampMs {
    #[inline]
    pub const fn new(ms: u64) -> Self {
        Self(ms)
    }

    #[inline]
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    #[inline]
    pub const fn saturating_sub(self, earlier: Self) -> u64 {
        self.0.saturating_sub(earlier.0)
    }
}

/// Normalized trackpad/touch gesture phase for smooth pixel deltas.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum ScrollTouchPhase {
    #[default]
    None = 0,
    Started = 1,
    Moved = 2,
    Ended = 3,
    Cancelled = 4,
}

/// Scroll input modality driving chaining, wheel smoothing, and rubber-band/momentum physics.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollInputKind {
    /// Discrete mouse-wheel detents (deltas already scaled into logical pixels).
    DiscreteLines,
    /// Continuous trackpad / touch pixel deltas with gesture phase and monotonic millisecond clock.
    SmoothPixels {
        phase: ScrollTouchPhase,
        timestamp_ms: u64,
    },
    /// Immediate deterministic delta without wheel smoothing or rubber-band animation.
    Instant,
}

/// Axis selector for per-axis scroll physics callbacks.
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ScrollAxis {
    X = 0,
    Y = 1,
}

/// Default logical pixels per discrete mouse-wheel line detent (`48.0` on Windows, `40.0`
/// elsewhere).
#[inline]
pub const fn default_px_per_line() -> f32 {
    #[cfg(target_os = "windows")]
    {
        48.0
    }
    #[cfg(not(target_os = "windows"))]
    {
        40.0
    }
}

/// Cross-platform `Shift+Wheel` normalization (zero macOS double-swap):
/// swaps `(0, dy) -> (dy, 0)` only when `shift` is held and `dx` is effectively zero.
/// macOS AppKit pre-swaps `Shift+Wheel` to `(dx, 0)`, so `dx.abs() >= 1e-4` makes this a no-op;
/// 2-axis trackpads and unshifted vertical wheels over horizontal carousels remain untouched.
#[inline]
pub fn normalize_shift_wheel(dx: f32, dy: f32, shift: bool) -> (f32, f32) {
    let dx = if dx.is_finite() { dx } else { 0.0 };
    let dy = if dy.is_finite() { dy } else { 0.0 };
    if shift && dx.abs() < 1e-4 && dy.abs() >= 1e-4 {
        (dy, 0.0)
    } else {
        (dx, dy)
    }
}

/// Read-only per-container context passed to [`ScrollPhysicsEngine::on_scroll_delta`] during
/// nested ancestor scroll chaining.
#[derive(Clone, Copy)]
pub struct ScrollContainerCtx<'a> {
    pub store: &'a NodeStore,
    pub node: NodeId,
    pub viewport: (f32, f32),
    pub offset: (f32, f32),
    pub max_offset: (f32, f32),
    pub allow_axes: (bool, bool),
    pub overscroll_behavior: (OverscrollBehavior, OverscrollBehavior),
    pub bounce_requested: bool,
}

/// Per-container delta consumption outcome written by [`ScrollPhysicsEngine::on_scroll_delta`].
#[derive(Debug, Clone, Copy, Default)]
pub struct ScrollDeltaResult {
    /// Updated clamped scroll offset `(x, y)` (pre-initialized to `ctx.offset`).
    pub next_offset: (f32, f32),
    /// Remaining unconsumed delta `(rem_x, rem_y)` to propagate to ancestor containers
    /// (already zeroed on axes blocked by `OverscrollBehavior::{Contain, None}`).
    pub remaining: (f32, f32),
    /// Whether X / Y consumed any delta (overscroll unwind, wheel easing, or clamped scroll).
    pub consumed_x: bool,
    pub consumed_y: bool,
    /// Whether visual presentation (clamped offset, overscroll, or animation state) changed.
    pub visual_changed: bool,
    /// Whether the clamped scroll offset changed (emits `ScrollEvent::Scroll` & a11y updates).
    pub clamped_changed: bool,
    /// Whether this container is eligible to absorb leftover `Auto`-chain overscroll on X / Y
    /// if no ancestor consumes the remaining delta.
    pub auto_overscroll_x: bool,
    pub auto_overscroll_y: bool,
}

/// Read-only scroll container bounds lookup passed to [`ScrollPhysicsEngine::on_gesture_start`]
/// and [`ScrollPhysicsEngine::step`] so engines can resolve ancestor bounds and top-layer overlay
/// boundaries without allocating.
pub trait ScrollBoundsLookup {
    /// Returns `(viewport_w, viewport_h, max_x, max_y)` for `node`, or `None` if unlaid-out.
    fn scroll_bounds(&self, store: &NodeStore, node: NodeId) -> Option<(f32, f32, f32, f32)>;

    /// Returns `true` when `node` is an open top-layer overlay root whose scroll chain must not
    /// cross into DOM ancestors behind it.
    #[inline]
    fn is_top_layer_boundary(&self, _node: NodeId) -> bool {
        false
    }
}

/// Pluggable per-surface scroll physics engine (Tier 3 surface-level engine trait).
///
/// Any physics engine (analytical decay/spring, RK4 integrator, Flutter `Simulation`, external
/// physics library) can implement this trait directly and install onto [`crate::LaidOutScene`]
/// via [`crate::LaidOutScene::set_scroll_physics`].
pub trait ScrollPhysicsEngine: Send {
    /// Consumes `(dx, dy)` on one scroll container along the ancestor chain.
    ///
    /// `out` is pre-initialized with `next_offset = ctx.offset`, `remaining = (dx, dy)`, and
    /// `false` flags. Implementations mutate `out` in-place with zero steady-state allocations.
    fn on_scroll_delta(
        &mut self,
        ctx: &ScrollContainerCtx<'_>,
        dx: f32,
        dy: f32,
        kind: ScrollInputKind,
        out: &mut ScrollDeltaResult,
    );

    /// Called on `ScrollTouchPhase::Started` to latch `start`, catch in-flight animations on its
    /// ancestor chain (stopping at top-layer overlay boundaries), and finalize abandoned drags on
    /// other containers.
    fn on_gesture_start(
        &mut self,
        _store: &NodeStore,
        _bounds: &dyn ScrollBoundsLookup,
        _start: NodeId,
        _now_ms: ScrollTimestampMs,
    ) {
    }

    /// Returns the currently latched gesture target node, if any.
    fn latched_target(&self) -> Option<NodeId> {
        None
    }

    /// Updates monotonic gesture timestamp on `ScrollTouchPhase::Moved`.
    fn on_gesture_move(&mut self, _now_ms: ScrollTimestampMs) {}

    /// Feeds leftover unconsumed `OverscrollBehavior::Auto` delta into the outermost eligible
    /// container on `axis`. Returns `true` if visual overscroll changed.
    fn on_outermost_overscroll(
        &mut self,
        _ctx: &ScrollContainerCtx<'_>,
        _axis: ScrollAxis,
        _rem: f32,
        _kind: ScrollInputKind,
    ) -> bool {
        false
    }

    /// Called when a phased trackpad/touch gesture ends or is cancelled, transitioning active
    /// drags into fling momentum, snap animations, or boundary return springs. Any immediate
    /// clamped offset changes must push affected node IDs into both `out_visual` and `out_clamped`.
    fn on_gesture_end(
        &mut self,
        _store: &NodeStore,
        _scroll: &mut ScrollOffsets,
        _now_ms: ScrollTimestampMs,
        _cancelled: bool,
        _out_visual: &mut Vec<NodeId>,
        _out_clamped: &mut Vec<NodeId>,
    ) {
    }

    /// Advances all active scroll animations by `dt_s` seconds, writing clamped offset updates
    /// into `scroll` and pushing affected container IDs into `out_visual` / `out_clamped` with
    /// zero steady-state heap allocations. Returns `true` while any animation remains active.
    fn step(
        &mut self,
        _store: &NodeStore,
        _bounds: &dyn ScrollBoundsLookup,
        _scroll: &mut ScrollOffsets,
        _dt_s: f32,
        _out_visual: &mut Vec<NodeId>,
        _out_clamped: &mut Vec<NodeId>,
    ) -> bool {
        false
    }

    /// Active visual overscroll `(ox, oy)` for `node` (`(0.0, 0.0)` when idle).
    fn overscroll(&self, _node: NodeId) -> (f32, f32) {
        (0.0, 0.0)
    }

    /// Whether any container currently has an active animation requiring vsync frames.
    fn has_active(&self) -> bool {
        false
    }

    /// Logical pixels per discrete mouse-wheel line detent.
    fn px_per_line(&self) -> f32 {
        default_px_per_line()
    }

    /// Cancels any active animation, drag, or overscroll state for `node`.
    fn cancel_node(&mut self, _node: NodeId) {}

    /// Reconciles active physics bounds/offsets across layout commits without killing active
    /// momentum unless `explicit_seek` is `true`.
    fn reconcile_node(
        &mut self,
        node: NodeId,
        _new_pos: (f32, f32),
        _max: (f32, f32),
        _anchor_delta: (f32, f32),
        explicit_seek: bool,
    ) {
        if explicit_seek {
            self.cancel_node(node);
        }
    }

    /// Prunes state for nodes that are no longer live `Scroll` containers in `store`.
    fn prune_missing(&mut self, _store: &NodeStore) {}

    /// Clears all internal physics and gesture state (called on [`crate::LaidOutScene::reset`]).
    fn clear(&mut self) {}

    /// Updates reduced-motion mode. When `reduced` is `true`, engines snap active smooth-wheel
    /// animations to their targets, updating `scroll` and pushing snapped nodes into
    /// `out_visual`/`out_clamped`. Returns `true` if any node snapped.
    fn set_reduced_motion(
        &mut self,
        _reduced: bool,
        _scroll: &mut ScrollOffsets,
        _out_visual: &mut Vec<NodeId>,
        _out_clamped: &mut Vec<NodeId>,
    ) -> bool {
        false
    }

    /// Controls whether phased trackpad/touch releases spawn synthetic momentum (`false` on macOS
    /// by default because AppKit delivers native OS momentum via `PixelDelta`).
    fn set_synthetic_momentum(&mut self, _enabled: bool) {}
}

/// Zero-size, zero-allocation default [`ScrollPhysicsEngine`]: immediate clamped scroll offsets
/// honoring `Scroll::axes` and `OverscrollBehavior::{Auto, Contain, None}` with zero animations
/// and zero memory overhead (`size_of::<InstantScrollPhysics>() == 0`).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct InstantScrollPhysics;

const _: () = assert!(std::mem::size_of::<InstantScrollPhysics>() == 0);

impl InstantScrollPhysics {
    #[inline]
    fn apply_axis(
        allow: bool,
        ob: OverscrollBehavior,
        cur: f32,
        max: f32,
        mut rem: f32,
    ) -> (f32, f32, bool) {
        if !rem.is_finite() {
            return (cur, 0.0, false);
        }
        if rem.abs() <= 1e-4 {
            return (cur, rem, false);
        }
        let mut next = cur;
        let mut consumed = false;
        if allow && max > 0.0 {
            let used = (cur + rem).clamp(0.0, max) - cur;
            if used.abs() > 1e-4 {
                next = cur + used;
                rem -= used;
                consumed = true;
            }
        }
        if rem.abs() > 1e-4 && allow && ob != OverscrollBehavior::Auto {
            rem = 0.0;
        }
        (next, rem, consumed)
    }
}

impl ScrollPhysicsEngine for InstantScrollPhysics {
    fn on_scroll_delta(
        &mut self,
        ctx: &ScrollContainerCtx<'_>,
        dx: f32,
        dy: f32,
        _kind: ScrollInputKind,
        out: &mut ScrollDeltaResult,
    ) {
        let (next_x, rem_x, consumed_x) = Self::apply_axis(
            ctx.allow_axes.0,
            ctx.overscroll_behavior.0,
            ctx.offset.0,
            ctx.max_offset.0,
            dx,
        );
        let (next_y, rem_y, consumed_y) = Self::apply_axis(
            ctx.allow_axes.1,
            ctx.overscroll_behavior.1,
            ctx.offset.1,
            ctx.max_offset.1,
            dy,
        );
        let changed = consumed_x || consumed_y;
        out.next_offset = (next_x, next_y);
        out.remaining = (rem_x, rem_y);
        out.consumed_x = consumed_x;
        out.consumed_y = consumed_y;
        out.visual_changed = changed;
        out.clamped_changed = changed;
    }
}