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
//! Animation curve recorder and `< 5%` curve error comparator for P0 §3.3 & DoD verification.

use serde::{Deserialize, Serialize};

/// One frame sample of an animated numeric property (position, width, opacity, scale, etc.).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurveSample {
    pub t_ms: f64,
    pub value: f64,
}

/// Recorded curve for one component property, serializable to JSON for `tools/arc-ref/compare.mjs`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CurveTrace {
    pub component: String,
    pub property: String,
    pub samples: Vec<CurveSample>,
}

impl CurveTrace {
    pub fn new(component: impl Into<String>, property: impl Into<String>) -> Self {
        Self {
            component: component.into(),
            property: property.into(),
            samples: Vec::new(),
        }
    }

    pub fn push(&mut self, t_ms: f64, value: f64) {
        self.samples.push(CurveSample { t_ms, value });
    }

    /// Evaluates the trace at `t_ms` using piecewise linear interpolation between samples.
    pub fn sample_at(&self, t_ms: f64) -> Option<f64> {
        if self.samples.is_empty() {
            return None;
        }
        if t_ms <= self.samples[0].t_ms || self.samples.len() == 1 {
            return Some(self.samples[0].value);
        }
        for w in self.samples.windows(2) {
            if t_ms <= w[1].t_ms {
                let dt = (w[1].t_ms - w[0].t_ms).max(1e-9);
                let frac = ((t_ms - w[0].t_ms) / dt).clamp(0.0, 1.0);
                return Some(w[0].value + (w[1].value - w[0].value) * frac);
            }
        }
        self.samples.last().map(|s| s.value)
    }

    pub fn to_json_pretty(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

/// Computes the maximum normalized percentage error (`0.0..=100.0+`) between two animation curves,
/// normalized by the reference curve's value span (or `1.0` if constant).
///
/// Plan §3.3 / DoD threshold: `< 5.0%`.
pub fn max_curve_error_pct(actual: &CurveTrace, expected: &CurveTrace) -> f64 {
    if expected.samples.is_empty() || actual.samples.is_empty() {
        return 100.0;
    }
    let min_v = expected
        .samples
        .iter()
        .map(|s| s.value)
        .fold(f64::INFINITY, f64::min);
    let max_v = expected
        .samples
        .iter()
        .map(|s| s.value)
        .fold(f64::NEG_INFINITY, f64::max);
    let span = (max_v - min_v).abs().max(1.0);

    let mut max_err = 0.0_f64;
    for ref_sample in &expected.samples {
        if let Some(actual_val) = actual.sample_at(ref_sample.t_ms) {
            let err_pct = ((actual_val - ref_sample.value).abs() / span) * 100.0;
            max_err = max_err.max(err_pct);
        }
    }
    max_err
}

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

    #[test]
    fn curve_error_comparator_reports_normalized_percentage() {
        let mut expected = CurveTrace::new("switch", "thumb_x");
        let mut actual = CurveTrace::new("switch", "thumb_x");
        for i in 0..=10 {
            let t = i as f64 * 16.0;
            let v = i as f64 * 1.8; // 0..18px
            expected.push(t, v);
            actual.push(t, v + 0.36); // 0.36 / 18 = 2%
        }
        let err = max_curve_error_pct(&actual, &expected);
        assert!((err - 2.0).abs() < 1e-6);
        assert!(err < 5.0);
    }
}