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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Spring adapter over `gpui_kit::SpringConfig` / `gpui_kit::base::motion` matching
//! `motion-dom/dist/es/animation/generators/spring.mjs` frame-by-frame (< 0.5px error).

use std::time::Duration;

use arc_tokens::{CubicBezierSpec, SpringPhysics, SpringSpec};
use gpui_kit::{App, ElementId, SpringState, Window, base::TransitionId};

use crate::{bezier::CubicBezier, clock::motion_now};

const CRITICAL_EPSILON: f64 = 1e-5;
const GRANULAR_DELTA_THRESHOLD: f64 = 5.0;
const REST_SPEED_GRANULAR: f64 = 0.01;
const REST_SPEED_DEFAULT: f64 = 2.0;
const REST_DELTA_GRANULAR: f64 = 0.005;
const REST_DELTA_DEFAULT: f64 = 0.5;

/// Sample returned by [`SpringSolver::sample`] and [`arc_spring_with_options`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SpringSample {
    pub value: f32,
    pub velocity: f32,
    pub settled: bool,
}

/// Analytical spring solver ported directly from Motion's `spring.mjs`.
///
/// Supports underdamped (`ζ < 1`), critically damped (`ζ == 1`), and overdamped (`ζ > 1`)
/// regimes, Motion's granular vs default rest thresholds, initial velocity injection,
/// and mid-flight retargeting.
#[derive(Clone, Copy, Debug)]
pub struct SpringSolver {
    physics: SpringPhysics,
    origin: f64,
    target: f64,
    /// Initial velocity in units/sec (Motion convention: positive = moving in +direction).
    initial_velocity: f64,
    rest_speed: f64,
    rest_delta: f64,
}

impl SpringSolver {
    pub fn new(spec: SpringSpec, origin: f64, target: f64, initial_velocity: f64) -> Self {
        let physics = spec.resolve();
        let delta = target - origin;
        let is_granular = delta.abs() < GRANULAR_DELTA_THRESHOLD;
        let rest_speed = if is_granular {
            REST_SPEED_GRANULAR
        } else {
            REST_SPEED_DEFAULT
        };
        let rest_delta = if is_granular {
            REST_DELTA_GRANULAR
        } else {
            REST_DELTA_DEFAULT
        };
        // Motion drops inherited velocity on time-defined (`visualDuration`) springs.
        let vel = if physics.is_time_defined {
            0.0
        } else {
            initial_velocity
        };
        Self {
            physics,
            origin,
            target,
            initial_velocity: vel,
            rest_speed,
            rest_delta,
        }
    }

    pub fn with_rest_thresholds(mut self, rest_delta: f64, rest_speed: f64) -> Self {
        self.rest_delta = rest_delta;
        self.rest_speed = rest_speed;
        self
    }

    /// Evaluates position, velocity (units/sec), and rest status at elapsed `t_secs`.
    pub fn sample(&self, t_secs: f64) -> SpringSample {
        let t = t_secs.max(0.0);
        let stiffness = f64::from(self.physics.stiffness);
        let damping = f64::from(self.physics.damping);
        let mass = f64::from(self.physics.mass);

        let delta = self.target - self.origin;
        // Motion uses `s.velocity = -velocity_per_ms` so positive velocity moves toward target
        // when target > origin; in standard displacement `x0 = origin - target = -delta`,
        // `v0 = initial_velocity`.
        let x0 = -delta;
        let v0 = self.initial_velocity;

        let omega0 = (stiffness / mass).sqrt();
        let zeta = damping / (2.0 * (stiffness * mass).sqrt());
        let decay = zeta * omega0;

        let (x, v) = if zeta < 1.0 - CRITICAL_EPSILON {
            let omega_d = omega0 * (1.0 - zeta * zeta).sqrt();
            let env = (-decay * t).exp();
            let (sin_wt, cos_wt) = (omega_d * t).sin_cos();
            let b = (v0 + decay * x0) / omega_d;
            let pos = env * (x0 * cos_wt + b * sin_wt);
            let vel =
                env * ((omega_d * b - decay * x0) * cos_wt - (omega_d * x0 + decay * b) * sin_wt);
            (pos, vel)
        } else if (zeta - 1.0).abs() <= CRITICAL_EPSILON {
            let env = (-omega0 * t).exp();
            let c2 = v0 + omega0 * x0;
            let pos = env * (x0 + c2 * t);
            let vel = env * (v0 - omega0 * c2 * t);
            (pos, vel)
        } else {
            let omega_d = omega0 * (zeta * zeta - 1.0).sqrt();
            let slow = decay - omega_d;
            let fast = decay + omega_d;
            let limit = if self.physics.is_time_defined {
                f64::INFINITY
            } else {
                300.0 / omega_d
            };
            let decay_at = |rate: f64| -> f64 {
                if t > limit {
                    (-rate * limit - decay * (t - limit)).exp()
                } else {
                    (-rate * t).exp()
                }
            };
            let p = (v0 + decay * x0) / omega_d;
            let s_coeff = 0.5 * (x0 + p);
            let f_coeff = 0.5 * (x0 - p);
            let e_slow = decay_at(slow);
            let e_fast = decay_at(fast);
            let pos = s_coeff * e_slow + f_coeff * e_fast;
            let vel = -slow * s_coeff * e_slow - fast * f_coeff * e_fast;
            (pos, vel)
        };

        let value = self.target + x;
        let settled = v.abs() <= self.rest_speed && (self.target - value).abs() <= self.rest_delta;
        SpringSample {
            value: (if settled { self.target } else { value }) as f32,
            velocity: (if settled { 0.0 } else { v }) as f32,
            settled,
        }
    }

    /// Retargets the spring from its current `(position, velocity)` to `new_target`.
    pub fn retarget(&mut self, current_value: f64, current_velocity: f64, new_target: f64) {
        self.origin = current_value;
        self.target = new_target;
        self.initial_velocity = if self.physics.is_time_defined {
            0.0
        } else {
            current_velocity
        };
        let is_granular = (new_target - current_value).abs() < GRANULAR_DELTA_THRESHOLD;
        self.rest_speed = if is_granular {
            REST_SPEED_GRANULAR
        } else {
            REST_SPEED_DEFAULT
        };
        self.rest_delta = if is_granular {
            REST_DELTA_GRANULAR
        } else {
            REST_DELTA_DEFAULT
        };
    }
}

/// Persistent state for a keyed `arc_spring` channel.
#[derive(Clone, Copy, Debug)]
pub struct SpringChannelState {
    pub state: SpringState,
    pub target: f32,
    pub updated_at_secs: f64,
    pub initialized: bool,
}

/// Options for [`arc_spring_with_options`].
#[derive(Clone, Copy, Debug)]
pub struct SpringOptions {
    pub spec: SpringSpec,
    /// When `false`, tracks the target immediately without lagging (e.g., active pointer drag).
    pub travel: bool,
    /// Optional starting position used only when this keyed channel mounts for the first time.
    pub initial_value: Option<f32>,
    /// Optional explicit velocity impulse (units/sec) injected on target change or trigger.
    pub initial_velocity: Option<f32>,
    /// Optional custom settling epsilon in target units (defaults to Motion granular/default).
    pub rest_delta: Option<f32>,
    pub rest_speed: Option<f32>,
}

impl SpringOptions {
    pub const fn new(spec: SpringSpec) -> Self {
        Self {
            spec,
            travel: true,
            initial_value: None,
            initial_velocity: None,
            rest_delta: None,
            rest_speed: None,
        }
    }

    pub const fn with_travel(mut self, travel: bool) -> Self {
        self.travel = travel;
        self
    }

    pub const fn with_initial_value(mut self, value: f32) -> Self {
        self.initial_value = Some(value);
        self
    }

    pub const fn with_initial_velocity(mut self, velocity: f32) -> Self {
        self.initial_velocity = Some(velocity);
        self
    }

    pub const fn with_rest_thresholds(mut self, rest_delta: f32, rest_speed: f32) -> Self {
        self.rest_delta = Some(rest_delta);
        self.rest_speed = Some(rest_speed);
        self
    }
}

/// Keyed spring hook respecting Arc `SpringSpec`, `MotionClock` (0.25x slow-mo),
/// `cx.reduce_motion()`, and `gpui::SpringConfig` velocity preservation.
pub fn arc_spring(
    id: impl Into<TransitionId>,
    target: f32,
    spec: SpringSpec,
    window: &mut Window,
    cx: &mut App,
) -> f32 {
    arc_spring_with_options(id, target, SpringOptions::new(spec), window, cx).value
}

/// Full-featured keyed spring hook returning position, velocity, and settled flag.
pub fn arc_spring_with_options(
    id: impl Into<TransitionId>,
    target: f32,
    options: SpringOptions,
    window: &mut Window,
    cx: &mut App,
) -> SpringSample {
    let target = if target.is_finite() { target } else { 0.0 };
    let element_id: ElementId =
        ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-spring".into());
    let now = motion_now(cx);
    let seed_pos = options
        .initial_value
        .filter(|v| v.is_finite())
        .unwrap_or(target);
    let state = window.use_keyed_state(element_id, cx, |_, _| SpringChannelState {
        state: SpringState {
            position: seed_pos,
            velocity: 0.0,
        },
        target,
        updated_at_secs: now,
        initialized: true,
    });

    let snapshot = *state.read(cx);

    if cx.reduce_motion() || !options.travel {
        if snapshot.state.position != target || snapshot.state.velocity != 0.0 {
            state.update(cx, |s, _| {
                s.state = SpringState {
                    position: target,
                    velocity: 0.0,
                };
                s.target = target;
                s.updated_at_secs = now;
            });
        }
        return SpringSample {
            value: target,
            velocity: 0.0,
            settled: true,
        };
    }

    let target_changed = (snapshot.target - target).abs() > 1e-6;
    let at_rest = !target_changed
        && (snapshot.state.position - target).abs() <= 1e-6
        && snapshot.state.velocity == 0.0
        && options.initial_velocity.is_none();

    if at_rest {
        return SpringSample {
            value: target,
            velocity: 0.0,
            settled: true,
        };
    }

    let physics = options.spec.resolve();
    let config = physics.to_gpui_config();

    let mut current_state = snapshot.state;
    let was_resting_on_old_target =
        (snapshot.state.position - snapshot.target).abs() <= 1e-6 && snapshot.state.velocity == 0.0;
    let elapsed = (now - snapshot.updated_at_secs).max(0.0) as f32;
    if elapsed > 0.0 && !was_resting_on_old_target {
        current_state = config.step(current_state, snapshot.target, elapsed);
    }

    if let Some(injected) = options.initial_velocity
        && injected.is_finite()
    {
        current_state.velocity = injected;
    } else if target_changed && physics.is_time_defined {
        // Match Motion's time-defined spring rule: avoid velocity spikes on small ranges.
        current_state.velocity = 0.0;
    }
    if !current_state.position.is_finite() || !current_state.velocity.is_finite() {
        current_state = SpringState {
            position: target,
            velocity: 0.0,
        };
    }

    let is_granular = (target - current_state.position).abs() < GRANULAR_DELTA_THRESHOLD as f32;
    let rest_delta = options.rest_delta.unwrap_or(if is_granular {
        REST_DELTA_GRANULAR as f32
    } else {
        REST_DELTA_DEFAULT as f32
    });
    let rest_speed = options.rest_speed.unwrap_or(if is_granular {
        REST_SPEED_GRANULAR as f32
    } else {
        REST_SPEED_DEFAULT as f32
    });

    let settled = (current_state.position - target).abs() <= rest_delta
        && current_state.velocity.abs() <= rest_speed;

    if settled {
        state.update(cx, |s, _| {
            s.state = SpringState {
                position: target,
                velocity: 0.0,
            };
            s.target = target;
            s.updated_at_secs = now;
        });
        SpringSample {
            value: target,
            velocity: 0.0,
            settled: true,
        }
    } else {
        state.update(cx, |s, _| {
            s.state = current_state;
            s.target = target;
            s.updated_at_secs = now;
        });
        window.request_animation_frame();
        SpringSample {
            value: current_state.position,
            velocity: current_state.velocity,
            settled: false,
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct ArcTransitionState {
    from: f32,
    target: f32,
    started_at_secs: f64,
    duration_secs: f64,
    curve: CubicBezier,
}

/// Keyed duration + cubic-bezier transition that honors `MotionClock` (0.25x slow-mo)
/// and `cx.reduce_motion()`.
pub fn arc_transition(
    id: impl Into<TransitionId>,
    target: f32,
    duration: Duration,
    ease: CubicBezierSpec,
    window: &mut Window,
    cx: &mut App,
) -> f32 {
    let element_id: ElementId =
        ElementId::NamedChild(ElementId::from(id.into()).into(), "__arc-transition".into());
    let now = motion_now(cx);
    let curve = CubicBezier::from_spec(ease);
    let duration_secs = duration.as_secs_f64();

    let state = window.use_keyed_state(element_id, cx, |_, _| ArcTransitionState {
        from: target,
        target,
        started_at_secs: now,
        duration_secs,
        curve,
    });

    let snapshot = *state.read(cx);

    if cx.reduce_motion() || duration_secs <= 0.0 {
        if snapshot.from != target || snapshot.target != target {
            state.update(cx, |s, _| {
                s.from = target;
                s.target = target;
                s.started_at_secs = now;
                s.duration_secs = duration_secs;
                s.curve = curve;
            });
        }
        return target;
    }

    let elapsed = (now - snapshot.started_at_secs).max(0.0);
    let raw_t = if snapshot.duration_secs <= 0.0 {
        1.0
    } else {
        (elapsed / snapshot.duration_secs).clamp(0.0, 1.0)
    };
    let eased = snapshot.curve.sample(raw_t as f32);
    let current = snapshot.from + (snapshot.target - snapshot.from) * eased;

    if (snapshot.target - target).abs() > 1e-6 {
        state.update(cx, |s, _| {
            s.from = current;
            s.target = target;
            s.started_at_secs = now;
            s.duration_secs = duration_secs;
            s.curve = curve;
        });
        window.request_animation_frame();
        current
    } else if (snapshot.from - snapshot.target).abs() <= 1e-6 || raw_t >= 1.0 {
        target
    } else {
        window.request_animation_frame();
        current
    }
}

#[cfg(test)]
mod tests {
    use arc_tokens::ArcMotionTokens;

    use super::*;

    /// Exact port of Motion's `spring.mjs` `resolveSpring` for 16ms frame-by-frame validation.
    fn motion_spring_at_ms(
        stiffness: f64,
        damping: f64,
        mass: f64,
        origin: f64,
        target: f64,
        velocity_per_sec: f64,
        t_ms: f64,
    ) -> f64 {
        let delta = target - origin;
        let damping_ratio = damping / (2.0 * (stiffness * mass).sqrt());
        let undamped_angular_freq = (stiffness / mass).sqrt() / 1000.0;
        let decay = damping_ratio * undamped_angular_freq;
        let v = -velocity_per_sec / 1000.0;

        if damping_ratio < 1.0 - 1e-5 {
            let angular_freq = undamped_angular_freq * (1.0 - damping_ratio * damping_ratio).sqrt();
            let a = (v + decay * delta) / angular_freq;
            let env = (-decay * t_ms).exp();
            target - env * (a * (angular_freq * t_ms).sin() + delta * (angular_freq * t_ms).cos())
        } else if (damping_ratio - 1.0).abs() <= 1e-5 {
            target
                - (-undamped_angular_freq * t_ms).exp()
                    * (delta + (v + undamped_angular_freq * delta) * t_ms)
        } else {
            let damped_freq = undamped_angular_freq * (damping_ratio * damping_ratio - 1.0).sqrt();
            let slow = decay - damped_freq;
            let fast = decay + damped_freq;
            let p = (v + decay * delta) / damped_freq;
            let s = 0.5 * (delta + p);
            let f = 0.5 * (delta - p);
            target - s * (-slow * t_ms).exp() - f * (-fast * t_ms).exp()
        }
    }

    #[test]
    fn frame_by_frame_matches_motion_within_0_5px_across_all_arc_presets() {
        let springs = ArcMotionTokens::DEFAULT.spring;
        let cases = [
            ("responsive", springs.responsive, 0.0, 200.0, 0.0),
            ("responsive_with_vel", springs.responsive, 0.0, 200.0, 450.0),
            ("gentle", springs.gentle, 20.0, 180.0, -120.0),
            ("snappy", springs.snappy, 0.0, 100.0, 0.0),
            ("smooth", springs.smooth, 0.0, 300.0, 0.0),
            ("morph", springs.morph, 40.0, 220.0, 0.0),
            (
                "elastic_snap_back",
                SpringSpec::visual(0.5, 0.42).as_physical(),
                26.0,
                0.0,
                -180.0,
            ),
            ("overdamped", SpringSpec::visual(0.4, -0.3), 0.0, 100.0, 0.0),
        ];

        for (name, spec, origin, target, velocity) in cases {
            let physics = spec.resolve();
            let solver = SpringSolver::new(spec, origin, target, velocity);
            let effective_vel = if physics.is_time_defined {
                0.0
            } else {
                velocity
            };
            let gpui_cfg = physics.to_gpui_config();
            let mut gpui_state = SpringState {
                position: origin as f32,
                velocity: effective_vel as f32,
            };

            let mut max_err_solver = 0.0_f64;
            let mut max_err_gpui = 0.0_f64;
            let dt_ms = 16.0_f64;
            for frame in 1..=60 {
                let t_ms = frame as f64 * dt_ms;
                let expected = motion_spring_at_ms(
                    f64::from(physics.stiffness),
                    f64::from(physics.damping),
                    f64::from(physics.mass),
                    origin,
                    target,
                    effective_vel,
                    t_ms,
                );
                let sample = solver.sample(t_ms / 1000.0);
                gpui_state = gpui_cfg.step(gpui_state, target as f32, (dt_ms / 1000.0) as f32);

                if !sample.settled {
                    max_err_solver = max_err_solver.max((f64::from(sample.value) - expected).abs());
                }
                max_err_gpui = max_err_gpui.max((f64::from(gpui_state.position) - expected).abs());
            }

            assert!(
                max_err_solver < 0.5,
                "SpringSolver '{name}' max error {max_err_solver}px >= 0.5px"
            );
            assert!(
                max_err_gpui < 0.5,
                "GPUI SpringConfig '{name}' max error {max_err_gpui}px >= 0.5px"
            );
        }
    }
}