arc-motion 0.1.0

Physics-first animation & motion engine for GPUI: analytical ODE springs, cubic bezier, FLIP shared layout, presence, drag/rubber-band, inertia, and SVG path morphing.
Documentation
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Drag gesture tracker, rubber-band elastic overscroll, deceleration projection, and
//! Motion's exact `inertia` decay + boundary bounce solver (`motion-dom/generators/inertia.mjs`).

use std::collections::VecDeque;

use arc_tokens::SpringSpec;

use crate::spring::SpringSolver;

/// iOS / Arc rubber-band resistance for a non-negative overscroll distance:
/// `(1 - 1 / (distance * 0.55 / dimension + 1)) * dimension`.
/// Identical to `elastic-slider.tsx` and `toast-stack.tsx`.
pub fn rubber_band(distance: f32, limit: f32) -> f32 {
    if limit <= 0.0 || distance <= 0.0 {
        return 0.0;
    }
    (1.0 - 1.0 / (distance * 0.55 / limit + 1.0)) * limit
}

/// Signed rubber-band resistance preserving direction (`elastic-slider.tsx`'s `rubber`).
pub fn rubber_band_signed(distance: f32, limit: f32) -> f32 {
    if distance == 0.0 {
        return 0.0;
    }
    distance.signum() * rubber_band(distance.abs(), limit)
}

/// Projects where a release at `velocity_px_per_sec` would come to rest under fast scroll
/// deceleration (`toast-stack.tsx`: `velocity / 1000 * 0.99 / (1 - 0.99)`).
pub fn project_deceleration(velocity_px_per_sec: f32) -> f32 {
    (velocity_px_per_sec / 1000.0) * 0.99 / (1.0 - 0.99)
}

/// Optional drag bounds with elastic overscroll limit.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct DragConstraints {
    pub min: Option<f32>,
    pub max: Option<f32>,
    /// Maximum elastic stretch past `min` / `max` (0.0 disables overscroll).
    pub elastic_limit: f32,
}

impl DragConstraints {
    pub fn apply(self, raw: f32) -> (f32, f32) {
        let mut clamped = raw;
        if let Some(min) = self.min {
            clamped = clamped.max(min);
        }
        if let Some(max) = self.max {
            clamped = clamped.min(max);
        }
        let excess = raw - clamped;
        let elastic = if self.elastic_limit > 0.0 {
            rubber_band_signed(excess, self.elastic_limit)
        } else {
            0.0
        };
        (clamped, elastic)
    }
}

/// Timestamped drag position sample.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DragSample {
    pub time_secs: f64,
    pub position: f32,
}

/// Tracks pointer drag with slop activation, rolling 100ms velocity window, and release throw.
#[derive(Clone, Debug)]
pub struct DragTracker {
    pub slop_px: f32,
    pub active: bool,
    start_x: f32,
    start_y: f32,
    origin_value: f32,
    samples: VecDeque<DragSample>,
}

impl DragTracker {
    pub fn new(slop_px: f32) -> Self {
        Self {
            slop_px: slop_px.max(0.0),
            active: false,
            start_x: 0.0,
            start_y: 0.0,
            origin_value: 0.0,
            samples: VecDeque::with_capacity(8),
        }
    }

    pub fn begin(&mut self, pointer_x: f32, pointer_y: f32, origin_value: f32, time_secs: f64) {
        self.active = self.slop_px == 0.0;
        self.start_x = pointer_x;
        self.start_y = pointer_y;
        self.origin_value = origin_value;
        self.samples.clear();
        if self.active {
            self.samples.push_back(DragSample {
                time_secs,
                position: origin_value,
            });
        }
    }

    /// Updates horizontal drag; returns `Some(raw_value)` once slop is passed, or `None` if
    /// still below slop (or cancelled by vertical dominance when `lock_horizontal` is true).
    pub fn update_x(
        &mut self,
        pointer_x: f32,
        pointer_y: f32,
        time_secs: f64,
        lock_horizontal: bool,
    ) -> Option<f32> {
        if !self.active {
            let dx = pointer_x - self.start_x;
            let dy = pointer_y - self.start_y;
            if dx.hypot(dy) < self.slop_px {
                return None;
            }
            if lock_horizontal && dy.abs() > dx.abs() {
                return None;
            }
            self.active = true;
            // Anchor start_x here so crossing slop never jumps, and start velocity samples cleanly.
            self.start_x = pointer_x;
            self.samples.clear();
        }
        let raw = self.origin_value + (pointer_x - self.start_x);
        self.samples.push_back(DragSample {
            time_secs,
            position: raw,
        });
        while self.samples.len() > 2 {
            if let Some(front) = self.samples.front()
                && time_secs - front.time_secs > 0.1
            {
                self.samples.pop_front();
                continue;
            }
            break;
        }
        Some(raw)
    }

    /// Computes release velocity in px/sec; returns `0.0` if the pointer paused > 60ms before lift.
    pub fn release_velocity(&self, release_time_secs: f64) -> f32 {
        let (Some(first), Some(last)) = (self.samples.front(), self.samples.back()) else {
            return 0.0;
        };
        let dt = last.time_secs - first.time_secs;
        if dt <= 0.008 || (release_time_secs - last.time_secs) > 0.060 {
            return 0.0;
        }
        ((last.position - first.position) as f64 / dt) as f32
    }
}

/// Configuration matching Motion's `inertia(...)` options in `motion-dom/generators/inertia.mjs`.
#[derive(Clone, Copy, Debug)]
pub struct InertiaConfig {
    pub power: f64,
    /// Time constant in milliseconds (Motion default: `325.0`).
    pub time_constant_ms: f64,
    pub bounce_stiffness: f64,
    pub bounce_damping: f64,
    pub min: Option<f64>,
    pub max: Option<f64>,
    pub rest_delta: f64,
}

impl Default for InertiaConfig {
    fn default() -> Self {
        Self {
            power: 0.8,
            time_constant_ms: 325.0,
            bounce_stiffness: 500.0,
            bounce_damping: 10.0,
            min: None,
            max: None,
            rest_delta: 0.5,
        }
    }
}

/// Sample returned by [`InertiaSolver::sample_ms`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct InertiaSample {
    pub value: f32,
    pub done: bool,
}

/// Exact port of Motion's `inertia` generator with friction decay + boundary spring catch.
#[derive(Clone, Debug)]
pub struct InertiaSolver {
    target: f64,
    amplitude: f64,
    config: InertiaConfig,
    boundary_time_ms: Option<f64>,
    boundary_spring: Option<SpringSolver>,
}

impl InertiaSolver {
    pub fn new(origin: f64, velocity_per_sec: f64, config: InertiaConfig) -> Self {
        let amplitude = config.power * velocity_per_sec;
        let target = origin + amplitude;
        let mut solver = Self {
            target,
            amplitude,
            config,
            boundary_time_ms: None,
            boundary_spring: None,
        };
        solver.check_boundary(0.0, origin);
        if solver.boundary_spring.is_none()
            && solver.is_out_of_bounds(target)
            && amplitude.abs() > 1e-9
            && config.time_constant_ms > 0.0
        {
            let boundary = solver.nearest_boundary(target);
            if (target - boundary).abs() > config.rest_delta {
                let ratio = ((target - boundary) / amplitude).clamp(1e-9, 1.0);
                let bt = (-config.time_constant_ms * ratio.ln()).max(0.0);
                solver.check_boundary(bt, boundary);
            }
        }
        solver
    }

    fn is_out_of_bounds(&self, v: f64) -> bool {
        self.config.min.is_some_and(|min| v < min) || self.config.max.is_some_and(|max| v > max)
    }

    fn nearest_boundary(&self, v: f64) -> f64 {
        match (self.config.min, self.config.max) {
            (Some(min), Some(max)) => {
                if (min - v).abs() < (max - v).abs() {
                    min
                } else {
                    max
                }
            }
            (Some(min), None) => min,
            (None, Some(max)) => max,
            (None, None) => v,
        }
    }

    fn calc_delta(&self, t_ms: f64) -> f64 {
        -self.amplitude * (-t_ms / self.config.time_constant_ms).exp()
    }

    fn check_boundary(&mut self, t_ms: f64, value: f64) {
        if self.boundary_spring.is_some() || !self.is_out_of_bounds(value) {
            return;
        }
        self.boundary_time_ms = Some(t_ms);
        let boundary = self.nearest_boundary(value);
        // Derivative of `target + calc_delta(t)` is `-calc_delta(t) / time_constant` (units/ms),
        // converted to units/sec for SpringSolver.
        let velocity_per_sec = (-self.calc_delta(t_ms) / self.config.time_constant_ms) * 1000.0;
        let spec = SpringSpec::physics(
            self.config.bounce_stiffness as f32,
            self.config.bounce_damping as f32,
        );
        self.boundary_spring = Some(
            SpringSolver::new(spec, value, boundary, velocity_per_sec)
                .with_rest_thresholds(self.config.rest_delta, 2.0),
        );
    }

    /// Evaluates the inertia curve at `t_ms` milliseconds since release.
    pub fn sample_ms(&mut self, t_ms: f64) -> InertiaSample {
        let t_ms = t_ms.max(0.0);
        if self.boundary_spring.is_none() {
            let delta = self.calc_delta(t_ms);
            let done = delta.abs() <= self.config.rest_delta;
            let value = if done {
                self.target
            } else {
                self.target + delta
            };
            self.check_boundary(t_ms, value);
            if self.boundary_spring.is_none() {
                return InertiaSample {
                    value: value as f32,
                    done,
                };
            }
        }

        if let (Some(bt), Some(spring)) = (self.boundary_time_ms, &self.boundary_spring)
            && t_ms >= bt
        {
            let s = spring.sample((t_ms - bt) / 1000.0);
            return InertiaSample {
                value: s.value,
                done: s.settled,
            };
        }

        let delta = self.calc_delta(t_ms);
        let done = delta.abs() <= self.config.rest_delta;
        let value = if done {
            self.target
        } else {
            self.target + delta
        };
        InertiaSample {
            value: value as f32,
            done,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rubber_band_is_monotonic_and_bounded_by_limit() {
        let limit = 26.0;
        assert_eq!(rubber_band_signed(0.0, limit), 0.0);
        let small = rubber_band_signed(10.0, limit);
        let large = rubber_band_signed(1000.0, limit);
        assert!(small > 0.0 && small < large && large < limit);
        assert!((rubber_band_signed(-10.0, limit) + small).abs() < 1e-5);
    }

    #[test]
    fn drag_tracker_handles_slop_and_velocity() {
        let mut tracker = DragTracker::new(6.0);
        tracker.begin(100.0, 50.0, 0.0, 0.0);
        assert_eq!(tracker.update_x(103.0, 50.0, 0.016, true), None);
        assert!(!tracker.active);

        // Cross slop at x = 110 -> anchored at 110 so no jump
        assert_eq!(tracker.update_x(110.0, 50.0, 0.032, true), Some(0.0));
        assert!(tracker.active);
        assert_eq!(tracker.update_x(160.0, 50.0, 0.082, true), Some(50.0));
        let vel = tracker.release_velocity(0.090);
        assert!((vel - 1000.0).abs() < 1.0, "expected ~1000px/s, got {vel}");
    }

    #[test]
    fn inertia_matches_motion_decay_and_bounces_at_boundary() {
        // Free decay (no boundaries)
        let mut free = InertiaSolver::new(0.0, 500.0, InertiaConfig::default());
        let s100 = free.sample_ms(100.0);
        let expected = 400.0 - 400.0 * (-100.0_f64 / 325.0).exp();
        assert!((f64::from(s100.value) - expected).abs() < 1e-3);

        // With max boundary at 100.0: crosses boundary and springs back to 100.0
        let cfg = InertiaConfig {
            min: Some(0.0),
            max: Some(100.0),
            ..Default::default()
        };
        let mut bounded = InertiaSolver::new(0.0, 800.0, cfg);
        let mut settled_value = 0.0;
        let mut reached_done = false;
        for step in 1..=200 {
            let s = bounded.sample_ms(step as f64 * 16.0);
            settled_value = s.value;
            if s.done {
                reached_done = true;
                break;
            }
        }
        assert!(reached_done);
        assert!((settled_value - 100.0).abs() <= 0.5);
    }
}