Skip to main content

arc_motion/
spring.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Spring adapter over `gpui_kit::SpringConfig` / `gpui_kit::base::motion` matching
3//! `motion-dom/dist/es/animation/generators/spring.mjs` frame-by-frame (< 0.5px error).
4
5use std::time::Duration;
6
7use arc_tokens::{CubicBezierSpec, SpringPhysics, SpringSpec};
8use gpui_kit::{App, ElementId, SpringState, Window, base::TransitionId};
9
10use crate::{bezier::CubicBezier, clock::motion_now};
11
12const CRITICAL_EPSILON: f64 = 1e-5;
13const GRANULAR_DELTA_THRESHOLD: f64 = 5.0;
14const REST_SPEED_GRANULAR: f64 = 0.01;
15const REST_SPEED_DEFAULT: f64 = 2.0;
16const REST_DELTA_GRANULAR: f64 = 0.005;
17const REST_DELTA_DEFAULT: f64 = 0.5;
18
19/// Sample returned by [`SpringSolver::sample`] and [`arc_spring_with_options`].
20#[derive(Clone, Copy, Debug, PartialEq)]
21pub struct SpringSample {
22    pub value: f32,
23    pub velocity: f32,
24    pub settled: bool,
25}
26
27/// Analytical spring solver ported directly from Motion's `spring.mjs`.
28///
29/// Supports underdamped (`ζ < 1`), critically damped (`ζ == 1`), and overdamped (`ζ > 1`)
30/// regimes, Motion's granular vs default rest thresholds, initial velocity injection,
31/// and mid-flight retargeting.
32#[derive(Clone, Copy, Debug)]
33pub struct SpringSolver {
34    physics: SpringPhysics,
35    origin: f64,
36    target: f64,
37    /// Initial velocity in units/sec (Motion convention: positive = moving in +direction).
38    initial_velocity: f64,
39    rest_speed: f64,
40    rest_delta: f64,
41}
42
43impl SpringSolver {
44    pub fn new(spec: SpringSpec, origin: f64, target: f64, initial_velocity: f64) -> Self {
45        let physics = spec.resolve();
46        let delta = target - origin;
47        let is_granular = delta.abs() < GRANULAR_DELTA_THRESHOLD;
48        let rest_speed = if is_granular {
49            REST_SPEED_GRANULAR
50        } else {
51            REST_SPEED_DEFAULT
52        };
53        let rest_delta = if is_granular {
54            REST_DELTA_GRANULAR
55        } else {
56            REST_DELTA_DEFAULT
57        };
58        // Motion drops inherited velocity on time-defined (`visualDuration`) springs.
59        let vel = if physics.is_time_defined {
60            0.0
61        } else {
62            initial_velocity
63        };
64        Self {
65            physics,
66            origin,
67            target,
68            initial_velocity: vel,
69            rest_speed,
70            rest_delta,
71        }
72    }
73
74    pub fn with_rest_thresholds(mut self, rest_delta: f64, rest_speed: f64) -> Self {
75        self.rest_delta = rest_delta;
76        self.rest_speed = rest_speed;
77        self
78    }
79
80    /// Evaluates position, velocity (units/sec), and rest status at elapsed `t_secs`.
81    pub fn sample(&self, t_secs: f64) -> SpringSample {
82        let t = t_secs.max(0.0);
83        let stiffness = f64::from(self.physics.stiffness);
84        let damping = f64::from(self.physics.damping);
85        let mass = f64::from(self.physics.mass);
86
87        let delta = self.target - self.origin;
88        // Motion uses `s.velocity = -velocity_per_ms` so positive velocity moves toward target
89        // when target > origin; in standard displacement `x0 = origin - target = -delta`,
90        // `v0 = initial_velocity`.
91        let x0 = -delta;
92        let v0 = self.initial_velocity;
93
94        let omega0 = (stiffness / mass).sqrt();
95        let zeta = damping / (2.0 * (stiffness * mass).sqrt());
96        let decay = zeta * omega0;
97
98        let (x, v) = if zeta < 1.0 - CRITICAL_EPSILON {
99            let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
100            let env = (-decay * t).exp();
101            let (sin_wt, cos_wt) = (omega_d * t).sin_cos();
102            let b = (v0 + decay * x0) / omega_d;
103            let pos = env * (x0 * cos_wt + b * sin_wt);
104            let vel =
105                env * ((omega_d * b - decay * x0) * cos_wt - (omega_d * x0 + decay * b) * sin_wt);
106            (pos, vel)
107        } else if (zeta - 1.0).abs() <= CRITICAL_EPSILON {
108            let env = (-omega0 * t).exp();
109            let c2 = v0 + omega0 * x0;
110            let pos = env * (x0 + c2 * t);
111            let vel = env * (v0 - omega0 * c2 * t);
112            (pos, vel)
113        } else {
114            let omega_d = omega0 * (zeta * zeta - 1.0).sqrt();
115            let slow = decay - omega_d;
116            let fast = decay + omega_d;
117            let limit = if self.physics.is_time_defined {
118                f64::INFINITY
119            } else {
120                300.0 / omega_d
121            };
122            let decay_at = |rate: f64| -> f64 {
123                if t > limit {
124                    (-rate * limit - decay * (t - limit)).exp()
125                } else {
126                    (-rate * t).exp()
127                }
128            };
129            let p = (v0 + decay * x0) / omega_d;
130            let s_coeff = 0.5 * (x0 + p);
131            let f_coeff = 0.5 * (x0 - p);
132            let e_slow = decay_at(slow);
133            let e_fast = decay_at(fast);
134            let pos = s_coeff * e_slow + f_coeff * e_fast;
135            let vel = -slow * s_coeff * e_slow - fast * f_coeff * e_fast;
136            (pos, vel)
137        };
138
139        let value = self.target + x;
140        let settled = v.abs() <= self.rest_speed && (self.target - value).abs() <= self.rest_delta;
141        SpringSample {
142            value: (if settled { self.target } else { value }) as f32,
143            velocity: (if settled { 0.0 } else { v }) as f32,
144            settled,
145        }
146    }
147
148    /// Retargets the spring from its current `(position, velocity)` to `new_target`.
149    pub fn retarget(&mut self, current_value: f64, current_velocity: f64, new_target: f64) {
150        self.origin = current_value;
151        self.target = new_target;
152        self.initial_velocity = if self.physics.is_time_defined {
153            0.0
154        } else {
155            current_velocity
156        };
157        let is_granular = (new_target - current_value).abs() < GRANULAR_DELTA_THRESHOLD;
158        self.rest_speed = if is_granular {
159            REST_SPEED_GRANULAR
160        } else {
161            REST_SPEED_DEFAULT
162        };
163        self.rest_delta = if is_granular {
164            REST_DELTA_GRANULAR
165        } else {
166            REST_DELTA_DEFAULT
167        };
168    }
169}
170
171/// Persistent state for a keyed `arc_spring` channel.
172#[derive(Clone, Copy, Debug)]
173pub struct SpringChannelState {
174    pub state: SpringState,
175    pub target: f32,
176    pub updated_at_secs: f64,
177    pub initialized: bool,
178}
179
180/// Options for [`arc_spring_with_options`].
181#[derive(Clone, Copy, Debug)]
182pub struct SpringOptions {
183    pub spec: SpringSpec,
184    /// When `false`, tracks the target immediately without lagging (e.g., active pointer drag).
185    pub travel: bool,
186    /// Optional starting position used only when this keyed channel mounts for the first time.
187    pub initial_value: Option<f32>,
188    /// Optional explicit velocity impulse (units/sec) injected on target change or trigger.
189    pub initial_velocity: Option<f32>,
190    /// Optional custom settling epsilon in target units (defaults to Motion granular/default).
191    pub rest_delta: Option<f32>,
192    pub rest_speed: Option<f32>,
193}
194
195impl SpringOptions {
196    pub const fn new(spec: SpringSpec) -> Self {
197        Self {
198            spec,
199            travel: true,
200            initial_value: None,
201            initial_velocity: None,
202            rest_delta: None,
203            rest_speed: None,
204        }
205    }
206
207    pub const fn with_travel(mut self, travel: bool) -> Self {
208        self.travel = travel;
209        self
210    }
211
212    pub const fn with_initial_value(mut self, value: f32) -> Self {
213        self.initial_value = Some(value);
214        self
215    }
216
217    pub const fn with_initial_velocity(mut self, velocity: f32) -> Self {
218        self.initial_velocity = Some(velocity);
219        self
220    }
221
222    pub const fn with_rest_thresholds(mut self, rest_delta: f32, rest_speed: f32) -> Self {
223        self.rest_delta = Some(rest_delta);
224        self.rest_speed = Some(rest_speed);
225        self
226    }
227}
228
229/// Keyed spring hook respecting Arc `SpringSpec`, `MotionClock` (0.25x slow-mo),
230/// `cx.reduce_motion()`, and `gpui::SpringConfig` velocity preservation.
231pub fn arc_spring(
232    id: impl Into<TransitionId>,
233    target: f32,
234    spec: SpringSpec,
235    window: &mut Window,
236    cx: &mut App,
237) -> f32 {
238    arc_spring_with_options(id, target, SpringOptions::new(spec), window, cx).value
239}
240
241/// Full-featured keyed spring hook returning position, velocity, and settled flag.
242pub fn arc_spring_with_options(
243    id: impl Into<TransitionId>,
244    target: f32,
245    options: SpringOptions,
246    window: &mut Window,
247    cx: &mut App,
248) -> SpringSample {
249    let target = if target.is_finite() { target } else { 0.0 };
250    let element_id: ElementId =
251        ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-spring".into());
252    let now = motion_now(cx);
253    let seed_pos = options
254        .initial_value
255        .filter(|v| v.is_finite())
256        .unwrap_or(target);
257    let state = window.use_keyed_state(element_id, cx, |_, _| SpringChannelState {
258        state: SpringState {
259            position: seed_pos,
260            velocity: 0.0,
261        },
262        target,
263        updated_at_secs: now,
264        initialized: true,
265    });
266
267    let snapshot = *state.read(cx);
268
269    if cx.reduce_motion() || !options.travel {
270        if snapshot.state.position != target || snapshot.state.velocity != 0.0 {
271            state.update(cx, |s, _| {
272                s.state = SpringState {
273                    position: target,
274                    velocity: 0.0,
275                };
276                s.target = target;
277                s.updated_at_secs = now;
278            });
279        }
280        return SpringSample {
281            value: target,
282            velocity: 0.0,
283            settled: true,
284        };
285    }
286
287    let target_changed = (snapshot.target - target).abs() > 1e-6;
288    let at_rest = !target_changed
289        && (snapshot.state.position - target).abs() <= 1e-6
290        && snapshot.state.velocity == 0.0
291        && options.initial_velocity.is_none();
292
293    if at_rest {
294        return SpringSample {
295            value: target,
296            velocity: 0.0,
297            settled: true,
298        };
299    }
300
301    let physics = options.spec.resolve();
302    let config = physics.to_gpui_config();
303
304    let mut current_state = snapshot.state;
305    let was_resting_on_old_target =
306        (snapshot.state.position - snapshot.target).abs() <= 1e-6 && snapshot.state.velocity == 0.0;
307    let elapsed = (now - snapshot.updated_at_secs).max(0.0) as f32;
308    if elapsed > 0.0 && !was_resting_on_old_target {
309        current_state = config.step(current_state, snapshot.target, elapsed);
310    }
311
312    if let Some(injected) = options.initial_velocity
313        && injected.is_finite()
314    {
315        current_state.velocity = injected;
316    } else if target_changed && physics.is_time_defined {
317        // Match Motion's time-defined spring rule: avoid velocity spikes on small ranges.
318        current_state.velocity = 0.0;
319    }
320    if !current_state.position.is_finite() || !current_state.velocity.is_finite() {
321        current_state = SpringState {
322            position: target,
323            velocity: 0.0,
324        };
325    }
326
327    let is_granular = (target - current_state.position).abs() < GRANULAR_DELTA_THRESHOLD as f32;
328    let rest_delta = options.rest_delta.unwrap_or(if is_granular {
329        REST_DELTA_GRANULAR as f32
330    } else {
331        REST_DELTA_DEFAULT as f32
332    });
333    let rest_speed = options.rest_speed.unwrap_or(if is_granular {
334        REST_SPEED_GRANULAR as f32
335    } else {
336        REST_SPEED_DEFAULT as f32
337    });
338
339    let settled = (current_state.position - target).abs() <= rest_delta
340        && current_state.velocity.abs() <= rest_speed;
341
342    if settled {
343        state.update(cx, |s, _| {
344            s.state = SpringState {
345                position: target,
346                velocity: 0.0,
347            };
348            s.target = target;
349            s.updated_at_secs = now;
350        });
351        SpringSample {
352            value: target,
353            velocity: 0.0,
354            settled: true,
355        }
356    } else {
357        state.update(cx, |s, _| {
358            s.state = current_state;
359            s.target = target;
360            s.updated_at_secs = now;
361        });
362        window.request_animation_frame();
363        SpringSample {
364            value: current_state.position,
365            velocity: current_state.velocity,
366            settled: false,
367        }
368    }
369}
370
371#[derive(Clone, Copy, Debug)]
372struct ArcTransitionState {
373    from: f32,
374    target: f32,
375    started_at_secs: f64,
376    duration_secs: f64,
377    curve: CubicBezier,
378}
379
380/// Keyed duration + cubic-bezier transition that honors `MotionClock` (0.25x slow-mo)
381/// and `cx.reduce_motion()`.
382pub fn arc_transition(
383    id: impl Into<TransitionId>,
384    target: f32,
385    duration: Duration,
386    ease: CubicBezierSpec,
387    window: &mut Window,
388    cx: &mut App,
389) -> f32 {
390    let element_id: ElementId =
391        ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-transition".into());
392    let now = motion_now(cx);
393    let curve = CubicBezier::from_spec(ease);
394    let duration_secs = duration.as_secs_f64();
395
396    let state = window.use_keyed_state(element_id, cx, |_, _| ArcTransitionState {
397        from: target,
398        target,
399        started_at_secs: now,
400        duration_secs,
401        curve,
402    });
403
404    let snapshot = *state.read(cx);
405
406    if cx.reduce_motion() || duration_secs <= 0.0 {
407        if snapshot.from != target || snapshot.target != target {
408            state.update(cx, |s, _| {
409                s.from = target;
410                s.target = target;
411                s.started_at_secs = now;
412                s.duration_secs = duration_secs;
413                s.curve = curve;
414            });
415        }
416        return target;
417    }
418
419    let elapsed = (now - snapshot.started_at_secs).max(0.0);
420    let raw_t = if snapshot.duration_secs <= 0.0 {
421        1.0
422    } else {
423        (elapsed / snapshot.duration_secs).clamp(0.0, 1.0)
424    };
425    let eased = snapshot.curve.sample(raw_t as f32);
426    let current = snapshot.from + (snapshot.target - snapshot.from) * eased;
427
428    if (snapshot.target - target).abs() > 1e-6 {
429        state.update(cx, |s, _| {
430            s.from = current;
431            s.target = target;
432            s.started_at_secs = now;
433            s.duration_secs = duration_secs;
434            s.curve = curve;
435        });
436        window.request_animation_frame();
437        current
438    } else if (snapshot.from - snapshot.target).abs() <= 1e-6 || raw_t >= 1.0 {
439        target
440    } else {
441        window.request_animation_frame();
442        current
443    }
444}
445
446#[cfg(test)]
447mod tests {
448    use arc_tokens::ArcMotionTokens;
449
450    use super::*;
451
452    /// Exact port of Motion's `spring.mjs` `resolveSpring` for 16ms frame-by-frame validation.
453    fn motion_spring_at_ms(
454        stiffness: f64,
455        damping: f64,
456        mass: f64,
457        origin: f64,
458        target: f64,
459        velocity_per_sec: f64,
460        t_ms: f64,
461    ) -> f64 {
462        let delta = target - origin;
463        let damping_ratio = damping / (2.0 * (stiffness * mass).sqrt());
464        let undamped_angular_freq = (stiffness / mass).sqrt() / 1000.0;
465        let decay = damping_ratio * undamped_angular_freq;
466        let v = -velocity_per_sec / 1000.0;
467
468        if damping_ratio < 1.0 - 1e-5 {
469            let angular_freq = undamped_angular_freq * (1.0 - damping_ratio * damping_ratio).sqrt();
470            let a = (v + decay * delta) / angular_freq;
471            let env = (-decay * t_ms).exp();
472            target - env * (a * (angular_freq * t_ms).sin() + delta * (angular_freq * t_ms).cos())
473        } else if (damping_ratio - 1.0).abs() <= 1e-5 {
474            target
475                - (-undamped_angular_freq * t_ms).exp()
476                    * (delta + (v + undamped_angular_freq * delta) * t_ms)
477        } else {
478            let damped_freq = undamped_angular_freq * (damping_ratio * damping_ratio - 1.0).sqrt();
479            let slow = decay - damped_freq;
480            let fast = decay + damped_freq;
481            let p = (v + decay * delta) / damped_freq;
482            let s = 0.5 * (delta + p);
483            let f = 0.5 * (delta - p);
484            target - s * (-slow * t_ms).exp() - f * (-fast * t_ms).exp()
485        }
486    }
487
488    #[test]
489    fn frame_by_frame_matches_motion_within_0_5px_across_all_arc_presets() {
490        let springs = ArcMotionTokens::DEFAULT.spring;
491        let cases = [
492            ("responsive", springs.responsive, 0.0, 200.0, 0.0),
493            ("responsive_with_vel", springs.responsive, 0.0, 200.0, 450.0),
494            ("gentle", springs.gentle, 20.0, 180.0, -120.0),
495            ("snappy", springs.snappy, 0.0, 100.0, 0.0),
496            ("smooth", springs.smooth, 0.0, 300.0, 0.0),
497            ("morph", springs.morph, 40.0, 220.0, 0.0),
498            (
499                "elastic_snap_back",
500                SpringSpec::visual(0.5, 0.42).as_physical(),
501                26.0,
502                0.0,
503                -180.0,
504            ),
505            ("overdamped", SpringSpec::visual(0.4, -0.3), 0.0, 100.0, 0.0),
506        ];
507
508        for (name, spec, origin, target, velocity) in cases {
509            let physics = spec.resolve();
510            let solver = SpringSolver::new(spec, origin, target, velocity);
511            let effective_vel = if physics.is_time_defined {
512                0.0
513            } else {
514                velocity
515            };
516            let gpui_cfg = physics.to_gpui_config();
517            let mut gpui_state = SpringState {
518                position: origin as f32,
519                velocity: effective_vel as f32,
520            };
521
522            let mut max_err_solver = 0.0_f64;
523            let mut max_err_gpui = 0.0_f64;
524            let dt_ms = 16.0_f64;
525            for frame in 1..=60 {
526                let t_ms = frame as f64 * dt_ms;
527                let expected = motion_spring_at_ms(
528                    f64::from(physics.stiffness),
529                    f64::from(physics.damping),
530                    f64::from(physics.mass),
531                    origin,
532                    target,
533                    effective_vel,
534                    t_ms,
535                );
536                let sample = solver.sample(t_ms / 1000.0);
537                gpui_state = gpui_cfg.step(gpui_state, target as f32, (dt_ms / 1000.0) as f32);
538
539                if !sample.settled {
540                    max_err_solver = max_err_solver.max((f64::from(sample.value) - expected).abs());
541                }
542                max_err_gpui = max_err_gpui.max((f64::from(gpui_state.position) - expected).abs());
543            }
544
545            assert!(
546                max_err_solver < 0.5,
547                "SpringSolver '{name}' max error {max_err_solver}px >= 0.5px"
548            );
549            assert!(
550                max_err_gpui < 0.5,
551                "GPUI SpringConfig '{name}' max error {max_err_gpui}px >= 0.5px"
552            );
553        }
554    }
555}