arc-motion 0.4.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
//! Subscribable `MotionValue<T>` with `map` (`useTransform`) and `velocity` (`useVelocity`).

use std::{cell::RefCell, collections::VecDeque, rc::Rc};

const VELOCITY_WINDOW_SECS: f64 = 0.1;

/// Piecewise linear mapping matching Motion's `useTransform(value, range_in, range_out, { clamp })`.
pub fn map_range(value: f32, range_in: &[f32], range_out: &[f32], clamp: bool) -> f32 {
    debug_assert_eq!(range_in.len(), range_out.len());
    debug_assert!(range_in.len() >= 2);
    if range_in.len() < 2 || range_out.len() != range_in.len() {
        return value;
    }

    let last = range_in.len() - 1;
    let ascending = range_in[last] >= range_in[0];

    if clamp {
        if ascending {
            if value <= range_in[0] {
                return range_out[0];
            }
            if value >= range_in[last] {
                return range_out[last];
            }
        } else {
            if value >= range_in[0] {
                return range_out[0];
            }
            if value <= range_in[last] {
                return range_out[last];
            }
        }
    }

    let mut seg = 0;
    for i in 0..last {
        let b = range_in[i + 1];
        if (ascending && value <= b) || (!ascending && value >= b) {
            seg = i;
            break;
        }
        seg = i;
    }

    let in_a = range_in[seg];
    let in_b = range_in[seg + 1];
    let out_a = range_out[seg];
    let out_b = range_out[seg + 1];
    let span = in_b - in_a;
    if span.abs() <= f32::EPSILON {
        return out_b;
    }
    let t = (value - in_a) / span;
    out_a + (out_b - out_a) * t
}

type ListenerFn<T> = Rc<dyn Fn(&T)>;
type Listener<T> = (usize, ListenerFn<T>);

struct Inner<T> {
    value: T,
    next_listener_id: usize,
    listeners: Vec<Listener<T>>,
    /// Timestamped scalar samples (time_secs, value) for velocity estimation when `T = f32`.
    samples: VecDeque<(f64, f32)>,
}

/// Subscribable reactive value (`f32`, `Point<Pixels>`, `Hsla`, etc.) with derived mapping
/// and velocity tracking.
#[derive(Clone)]
pub struct MotionValue<T> {
    inner: Rc<RefCell<Inner<T>>>,
}

impl<T: Clone + 'static> MotionValue<T> {
    pub fn new(initial: T) -> Self {
        Self {
            inner: Rc::new(RefCell::new(Inner {
                value: initial,
                next_listener_id: 1,
                listeners: Vec::new(),
                samples: VecDeque::with_capacity(8),
            })),
        }
    }

    pub fn get(&self) -> T {
        self.inner.borrow().value.clone()
    }

    pub fn set(&self, next: T)
    where
        T: PartialEq,
    {
        let listeners: Vec<ListenerFn<T>> = {
            let mut inner = self.inner.borrow_mut();
            if inner.value == next {
                return;
            }
            inner.value = next.clone();
            inner.listeners.iter().map(|(_, cb)| cb.clone()).collect()
        };
        for cb in listeners {
            cb(&next);
        }
    }

    /// Subscribe to value changes. Returns an unsubscribe handle ID.
    pub fn subscribe(&self, listener: impl Fn(&T) + 'static) -> usize {
        let mut inner = self.inner.borrow_mut();
        let id = inner.next_listener_id;
        inner.next_listener_id += 1;
        inner.listeners.push((id, Rc::new(listener)));
        id
    }

    pub fn unsubscribe(&self, id: usize) {
        self.inner
            .borrow_mut()
            .listeners
            .retain(|(lid, _)| *lid != id);
    }

    /// Creates a derived `MotionValue<U>` updated automatically whenever this value changes.
    pub fn map_fn<U: Clone + PartialEq + 'static>(
        &self,
        transform: impl Fn(&T) -> U + 'static,
    ) -> MotionValue<U> {
        let derived = MotionValue::new(transform(&self.get()));
        let derived_clone = derived.clone();
        self.subscribe(move |v| {
            derived_clone.set(transform(v));
        });
        derived
    }
}

impl MotionValue<f32> {
    /// Sets a scalar value with an explicit timestamp (seconds) so [`Self::velocity`] stays accurate.
    pub fn set_at(&self, next: f32, time_secs: f64) {
        let listeners: Vec<ListenerFn<f32>> = {
            let mut inner = self.inner.borrow_mut();
            inner.samples.push_back((time_secs, next));
            while inner.samples.len() > 2 {
                if let Some(&(first_t, _)) = inner.samples.front()
                    && time_secs - first_t > VELOCITY_WINDOW_SECS
                {
                    inner.samples.pop_front();
                    continue;
                }
                break;
            }
            if (inner.value - next).abs() <= f32::EPSILON {
                return;
            }
            inner.value = next;
            inner.listeners.iter().map(|(_, cb)| cb.clone()).collect()
        };
        for cb in listeners {
            cb(&next);
        }
    }

    /// Jumps to `next` and resets velocity history (matching Motion's `mv.jump(...)`).
    pub fn jump(&self, next: f32) {
        let listeners: Vec<ListenerFn<f32>> = {
            let mut inner = self.inner.borrow_mut();
            inner.samples.clear();
            inner.value = next;
            inner.listeners.iter().map(|(_, cb)| cb.clone()).collect()
        };
        for cb in listeners {
            cb(&next);
        }
    }

    /// Returns instantaneous velocity in units/sec (matching Motion's `useVelocity` / `getVelocity`).
    pub fn velocity(&self) -> f32 {
        let inner = self.inner.borrow();
        let (Some(&(t0, v0)), Some(&(t1, v1))) = (inner.samples.front(), inner.samples.back())
        else {
            return 0.0;
        };
        let dt = t1 - t0;
        if dt <= 1e-5 {
            return 0.0;
        }
        ((v1 - v0) as f64 / dt) as f32
    }

    /// Piecewise-linear derived value (`useTransform(mv, range_in, range_out, clamp)`).
    pub fn map(&self, range_in: Vec<f32>, range_out: Vec<f32>, clamp: bool) -> MotionValue<f32> {
        self.map_fn(move |&v| map_range(v, &range_in, &range_out, clamp))
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;

    use super::*;

    #[test]
    fn motion_value_map_and_clamp_work() {
        let x = MotionValue::new(0.0_f32);
        let opacity = x.map(vec![0.0, 280.0], vec![1.0, 0.25], true);
        assert!((opacity.get() - 1.0).abs() < 1e-5);

        x.set(140.0);
        assert!((opacity.get() - 0.625).abs() < 1e-5);

        x.set(500.0);
        assert!((opacity.get() - 0.25).abs() < 1e-5);

        x.set(-50.0);
        assert!((opacity.get() - 1.0).abs() < 1e-5);
    }

    #[test]
    fn motion_value_velocity_and_jump_reset() {
        let pos = MotionValue::new(0.0_f32);
        pos.set_at(0.0, 1.000);
        pos.set_at(50.0, 1.050);
        assert!((pos.velocity() - 1000.0).abs() < 1e-2);

        pos.jump(10.0);
        assert_eq!(pos.get(), 10.0);
        assert_eq!(pos.velocity(), 0.0);
    }

    #[test]
    fn motion_value_subscribe_and_unsubscribe() {
        let v = MotionValue::new(1.0_f32);
        let hits = Rc::new(Cell::new(0usize));
        let hits_clone = hits.clone();
        let sub = v.subscribe(move |_| hits_clone.set(hits_clone.get() + 1));
        v.set(2.0);
        v.set(2.0); // unchanged does not fire
        assert_eq!(hits.get(), 1);
        v.unsubscribe(sub);
        v.set(3.0);
        assert_eq!(hits.get(), 1);
    }
}