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/// 测量驱动的布局弹簧:未知尺寸只占位,首次真实测量直接落位,后续变化保留弹簧。
242/// 不给估算尺寸建立通道,避免组件挂载时把排版校正误播成入场动效。
243pub fn arc_measured_spring(
244    id: impl Into<TransitionId>,
245    measured: Option<f32>,
246    fallback: f32,
247    spec: SpringSpec,
248    window: &mut Window,
249    cx: &mut App,
250) -> f32 {
251    match measured.filter(|value| value.is_finite()) {
252        Some(target) => arc_spring(id, target, spec, window, cx),
253        None => fallback,
254    }
255}
256
257/// Full-featured keyed spring hook returning position, velocity, and settled flag.
258pub fn arc_spring_with_options(
259    id: impl Into<TransitionId>,
260    target: f32,
261    options: SpringOptions,
262    window: &mut Window,
263    cx: &mut App,
264) -> SpringSample {
265    let target = if target.is_finite() { target } else { 0.0 };
266    let element_id: ElementId =
267        ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-spring".into());
268    let now = motion_now(cx);
269    let seed_pos = options
270        .initial_value
271        .filter(|v| v.is_finite())
272        .unwrap_or(target);
273    let state = window.use_keyed_state(element_id, cx, |_, _| SpringChannelState {
274        state: SpringState {
275            position: seed_pos,
276            velocity: 0.0,
277        },
278        target,
279        updated_at_secs: now,
280        initialized: true,
281    });
282
283    let snapshot = *state.read(cx);
284
285    if cx.reduce_motion() || !options.travel {
286        if snapshot.state.position != target || snapshot.state.velocity != 0.0 {
287            state.update(cx, |s, _| {
288                s.state = SpringState {
289                    position: target,
290                    velocity: 0.0,
291                };
292                s.target = target;
293                s.updated_at_secs = now;
294            });
295        }
296        return SpringSample {
297            value: target,
298            velocity: 0.0,
299            settled: true,
300        };
301    }
302
303    let target_changed = (snapshot.target - target).abs() > 1e-6;
304    let at_rest = !target_changed
305        && (snapshot.state.position - target).abs() <= 1e-6
306        && snapshot.state.velocity == 0.0
307        && options.initial_velocity.is_none();
308
309    if at_rest {
310        return SpringSample {
311            value: target,
312            velocity: 0.0,
313            settled: true,
314        };
315    }
316
317    let physics = options.spec.resolve();
318    let config = physics.to_gpui_config();
319
320    let mut current_state = snapshot.state;
321    let was_resting_on_old_target =
322        (snapshot.state.position - snapshot.target).abs() <= 1e-6 && snapshot.state.velocity == 0.0;
323    let elapsed = (now - snapshot.updated_at_secs).max(0.0) as f32;
324    if elapsed > 0.0 && !was_resting_on_old_target {
325        current_state = config.step(current_state, snapshot.target, elapsed);
326    }
327
328    if let Some(injected) = options.initial_velocity
329        && injected.is_finite()
330    {
331        current_state.velocity = injected;
332    } else if target_changed && physics.is_time_defined {
333        // Match Motion's time-defined spring rule: avoid velocity spikes on small ranges.
334        current_state.velocity = 0.0;
335    }
336    if !current_state.position.is_finite() || !current_state.velocity.is_finite() {
337        current_state = SpringState {
338            position: target,
339            velocity: 0.0,
340        };
341    }
342
343    let is_granular = (target - current_state.position).abs() < GRANULAR_DELTA_THRESHOLD as f32;
344    let rest_delta = options.rest_delta.unwrap_or(if is_granular {
345        REST_DELTA_GRANULAR as f32
346    } else {
347        REST_DELTA_DEFAULT as f32
348    });
349    let rest_speed = options.rest_speed.unwrap_or(if is_granular {
350        REST_SPEED_GRANULAR as f32
351    } else {
352        REST_SPEED_DEFAULT as f32
353    });
354
355    let settled = (current_state.position - target).abs() <= rest_delta
356        && current_state.velocity.abs() <= rest_speed;
357
358    if settled {
359        state.update(cx, |s, _| {
360            s.state = SpringState {
361                position: target,
362                velocity: 0.0,
363            };
364            s.target = target;
365            s.updated_at_secs = now;
366        });
367        SpringSample {
368            value: target,
369            velocity: 0.0,
370            settled: true,
371        }
372    } else {
373        state.update(cx, |s, _| {
374            s.state = current_state;
375            s.target = target;
376            s.updated_at_secs = now;
377        });
378        window.request_animation_frame();
379        SpringSample {
380            value: current_state.position,
381            velocity: current_state.velocity,
382            settled: false,
383        }
384    }
385}
386
387#[derive(Clone, Copy, Debug)]
388struct ArcTransitionState {
389    from: f32,
390    target: f32,
391    started_at_secs: f64,
392    duration_secs: f64,
393    curve: CubicBezier,
394}
395
396/// Keyed duration + cubic-bezier transition that honors `MotionClock` (0.25x slow-mo)
397/// and `cx.reduce_motion()`.
398pub fn arc_transition(
399    id: impl Into<TransitionId>,
400    target: f32,
401    duration: Duration,
402    ease: CubicBezierSpec,
403    window: &mut Window,
404    cx: &mut App,
405) -> f32 {
406    let element_id: ElementId =
407        ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-transition".into());
408    let now = motion_now(cx);
409    let curve = CubicBezier::from_spec(ease);
410    let duration_secs = duration.as_secs_f64();
411
412    let state = window.use_keyed_state(element_id, cx, |_, _| ArcTransitionState {
413        from: target,
414        target,
415        started_at_secs: now,
416        duration_secs,
417        curve,
418    });
419
420    let snapshot = *state.read(cx);
421
422    if cx.reduce_motion() || duration_secs <= 0.0 {
423        if snapshot.from != target || snapshot.target != target {
424            state.update(cx, |s, _| {
425                s.from = target;
426                s.target = target;
427                s.started_at_secs = now;
428                s.duration_secs = duration_secs;
429                s.curve = curve;
430            });
431        }
432        return target;
433    }
434
435    let elapsed = (now - snapshot.started_at_secs).max(0.0);
436    let raw_t = if snapshot.duration_secs <= 0.0 {
437        1.0
438    } else {
439        (elapsed / snapshot.duration_secs).clamp(0.0, 1.0)
440    };
441    let eased = snapshot.curve.sample(raw_t as f32);
442    let current = snapshot.from + (snapshot.target - snapshot.from) * eased;
443
444    if (snapshot.target - target).abs() > 1e-6 {
445        state.update(cx, |s, _| {
446            s.from = current;
447            s.target = target;
448            s.started_at_secs = now;
449            s.duration_secs = duration_secs;
450            s.curve = curve;
451        });
452        window.request_animation_frame();
453        current
454    } else if (snapshot.from - snapshot.target).abs() <= 1e-6 || raw_t >= 1.0 {
455        target
456    } else {
457        window.request_animation_frame();
458        current
459    }
460}
461
462#[cfg(test)]
463mod tests {
464    use arc_tokens::ArcMotionTokens;
465
466    use super::*;
467
468    struct MeasuredHost {
469        measured: Option<f32>,
470        value: f32,
471    }
472    impl gpui_kit::Render for MeasuredHost {
473        fn render(
474            &mut self,
475            w: &mut Window,
476            cx: &mut gpui_kit::Context<Self>,
477        ) -> impl gpui_kit::IntoElement {
478            self.value = arc_measured_spring(
479                "measured-test",
480                self.measured,
481                36.0,
482                ArcMotionTokens::DEFAULT.spring.smooth,
483                w,
484                cx,
485            );
486            gpui_kit::div()
487        }
488    }
489    #[gpui_kit::test]
490    fn measured_spring_snaps_first_measurement_but_animates_later_changes(
491        cx: &mut gpui_kit::TestAppContext,
492    ) {
493        use gpui_kit::test::TestWindowExt as _;
494        let (view, cx) = cx.add_window_view(|_, _| MeasuredHost {
495            measured: None,
496            value: 0.0,
497        });
498        cx.update(|w, cx| {
499            w.render_frame(cx);
500            assert_eq!(view.read(cx).value, 36.0);
501        });
502        view.update(cx, |v, cx| {
503            v.measured = Some(104.0);
504            cx.notify();
505        });
506        cx.update(|w, cx| {
507            w.render_frame(cx);
508            assert_eq!(view.read(cx).value, 104.0);
509        });
510        view.update(cx, |v, cx| {
511            v.measured = Some(180.0);
512            cx.notify();
513        });
514        cx.update(|w, cx| {
515            w.render_frame(cx);
516            assert_eq!(view.read(cx).value, 104.0);
517        });
518        cx.executor().advance_clock(Duration::from_millis(32));
519        cx.update(|w, cx| {
520            w.render_frame(cx);
521            let value = view.read(cx).value;
522            assert!(value > 104.0 && value < 180.0);
523        });
524    }
525
526    /// Exact port of Motion's `spring.mjs` `resolveSpring` for 16ms frame-by-frame validation.
527    fn motion_spring_at_ms(
528        stiffness: f64,
529        damping: f64,
530        mass: f64,
531        origin: f64,
532        target: f64,
533        velocity_per_sec: f64,
534        t_ms: f64,
535    ) -> f64 {
536        let delta = target - origin;
537        let damping_ratio = damping / (2.0 * (stiffness * mass).sqrt());
538        let undamped_angular_freq = (stiffness / mass).sqrt() / 1000.0;
539        let decay = damping_ratio * undamped_angular_freq;
540        let v = -velocity_per_sec / 1000.0;
541
542        if damping_ratio < 1.0 - 1e-5 {
543            let angular_freq = undamped_angular_freq * (1.0 - damping_ratio * damping_ratio).sqrt();
544            let a = (v + decay * delta) / angular_freq;
545            let env = (-decay * t_ms).exp();
546            target - env * (a * (angular_freq * t_ms).sin() + delta * (angular_freq * t_ms).cos())
547        } else if (damping_ratio - 1.0).abs() <= 1e-5 {
548            target
549                - (-undamped_angular_freq * t_ms).exp()
550                    * (delta + (v + undamped_angular_freq * delta) * t_ms)
551        } else {
552            let damped_freq = undamped_angular_freq * (damping_ratio * damping_ratio - 1.0).sqrt();
553            let slow = decay - damped_freq;
554            let fast = decay + damped_freq;
555            let p = (v + decay * delta) / damped_freq;
556            let s = 0.5 * (delta + p);
557            let f = 0.5 * (delta - p);
558            target - s * (-slow * t_ms).exp() - f * (-fast * t_ms).exp()
559        }
560    }
561
562    #[test]
563    fn frame_by_frame_matches_motion_within_0_5px_across_all_arc_presets() {
564        let springs = ArcMotionTokens::DEFAULT.spring;
565        let cases = [
566            ("responsive", springs.responsive, 0.0, 200.0, 0.0),
567            ("responsive_with_vel", springs.responsive, 0.0, 200.0, 450.0),
568            ("gentle", springs.gentle, 20.0, 180.0, -120.0),
569            ("snappy", springs.snappy, 0.0, 100.0, 0.0),
570            ("smooth", springs.smooth, 0.0, 300.0, 0.0),
571            ("morph", springs.morph, 40.0, 220.0, 0.0),
572            (
573                "elastic_snap_back",
574                SpringSpec::visual(0.5, 0.42).as_physical(),
575                26.0,
576                0.0,
577                -180.0,
578            ),
579            ("overdamped", SpringSpec::visual(0.4, -0.3), 0.0, 100.0, 0.0),
580        ];
581
582        for (name, spec, origin, target, velocity) in cases {
583            let physics = spec.resolve();
584            let solver = SpringSolver::new(spec, origin, target, velocity);
585            let effective_vel = if physics.is_time_defined {
586                0.0
587            } else {
588                velocity
589            };
590            let gpui_cfg = physics.to_gpui_config();
591            let mut gpui_state = SpringState {
592                position: origin as f32,
593                velocity: effective_vel as f32,
594            };
595
596            let mut max_err_solver = 0.0_f64;
597            let mut max_err_gpui = 0.0_f64;
598            let dt_ms = 16.0_f64;
599            for frame in 1..=60 {
600                let t_ms = frame as f64 * dt_ms;
601                let expected = motion_spring_at_ms(
602                    f64::from(physics.stiffness),
603                    f64::from(physics.damping),
604                    f64::from(physics.mass),
605                    origin,
606                    target,
607                    effective_vel,
608                    t_ms,
609                );
610                let sample = solver.sample(t_ms / 1000.0);
611                gpui_state = gpui_cfg.step(gpui_state, target as f32, (dt_ms / 1000.0) as f32);
612
613                if !sample.settled {
614                    max_err_solver = max_err_solver.max((f64::from(sample.value) - expected).abs());
615                }
616                max_err_gpui = max_err_gpui.max((f64::from(gpui_state.position) - expected).abs());
617            }
618
619            assert!(
620                max_err_solver < 0.5,
621                "SpringSolver '{name}' max error {max_err_solver}px >= 0.5px"
622            );
623            assert!(
624                max_err_gpui < 0.5,
625                "GPUI SpringConfig '{name}' max error {max_err_gpui}px >= 0.5px"
626            );
627        }
628    }
629}