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
//! Presence convention over `gpui_kit::base::Presence` enforcing Arc's asymmetric
//! enter/exit timing (`ease.enter` + `duration.standard` vs `ease.exit` + `duration.exit`),
//! mid-exit reversal, and slow-motion clock support.

use std::time::Duration;

use arc_tokens::{ArcMotionTokens, CubicBezierSpec};
use gpui_kit::{
    App, ElementId, Window,
    base::{MotionStatus, PresencePhase, TransitionId},
};

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

/// Enter/exit timing configuration for [`ArcPresence`].
#[derive(Clone, Copy, Debug)]
pub struct ArcPresenceConfig {
    pub enter_duration: Duration,
    pub enter_ease: CubicBezierSpec,
    pub exit_duration: Duration,
    pub exit_ease: CubicBezierSpec,
    /// When true, reduced motion still runs a short fade (`duration.instant`) instead of snapping.
    pub fade_on_reduced_motion: bool,
}

impl Default for ArcPresenceConfig {
    fn default() -> Self {
        let tokens = ArcMotionTokens::DEFAULT;
        Self {
            enter_duration: tokens.duration.standard,
            enter_ease: tokens.ease.enter,
            exit_duration: tokens.duration.exit,
            exit_ease: tokens.ease.exit,
            fade_on_reduced_motion: false,
        }
    }
}

/// Sample returned by [`ArcPresence::sample`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ArcPresenceSample {
    pub phase: PresencePhase,
    /// Eased progress in `0.0..=1.0` (`0.0` = absent, `1.0` = fully present).
    pub progress: f32,
    pub status: MotionStatus,
}

impl ArcPresenceSample {
    pub const fn should_render(self) -> bool {
        !matches!(self.phase, PresencePhase::Absent)
    }

    pub const fn is_exiting(self) -> bool {
        matches!(self.phase, PresencePhase::Exiting)
    }
}

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

/// Arc presence controller: asymmetric enter/exit curves + smooth mid-exit reversal.
pub struct ArcPresence {
    id: TransitionId,
    present: bool,
    config: ArcPresenceConfig,
    /// If true, first mount starts at `0.0` and enters; if false, first mount adopts `present`.
    animate_initial: bool,
}

impl ArcPresence {
    pub fn new(id: impl Into<TransitionId>, present: bool) -> Self {
        Self {
            id: id.into(),
            present,
            config: ArcPresenceConfig::default(),
            animate_initial: true,
        }
    }

    pub fn config(mut self, config: ArcPresenceConfig) -> Self {
        self.config = config;
        self
    }

    pub fn enter(mut self, duration: Duration, ease: CubicBezierSpec) -> Self {
        self.config.enter_duration = duration;
        self.config.enter_ease = ease;
        self
    }

    pub fn exit(mut self, duration: Duration, ease: CubicBezierSpec) -> Self {
        self.config.exit_duration = duration;
        self.config.exit_ease = ease;
        self
    }

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

    pub fn sample(self, window: &mut Window, cx: &mut App) -> ArcPresenceSample {
        let element_id =
            ElementId::NamedChild(ElementId::from(self.id).into(), "__arc-presence".into());
        let now = motion_now(cx);
        let target = if self.present { 1.0 } else { 0.0 };
        let reduced = cx.reduce_motion();

        let (duration, ease) = if self.present {
            (
                if reduced && self.config.fade_on_reduced_motion {
                    ArcMotionTokens::DEFAULT.duration.instant
                } else {
                    self.config.enter_duration
                },
                CubicBezier::from_spec(self.config.enter_ease),
            )
        } else {
            (
                if reduced && self.config.fade_on_reduced_motion {
                    ArcMotionTokens::DEFAULT.duration.instant
                } else {
                    self.config.exit_duration
                },
                CubicBezier::from_spec(self.config.exit_ease),
            )
        };

        let initial_from = if self.animate_initial { 0.0 } else { target };
        let state = window.use_keyed_state(element_id, cx, |_, _| PresenceState {
            from: initial_from,
            target,
            started_at_secs: now,
            duration_secs: duration.as_secs_f64(),
            ease,
        });
        let snapshot = *state.read(cx);

        if (reduced && !self.config.fade_on_reduced_motion) || duration.is_zero() {
            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 = 0.0;
                    s.ease = ease;
                });
            }
            return stable(self.present);
        }

        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.ease.sample(raw_t as f32);
        let sampled = snapshot.from + (snapshot.target - snapshot.from) * eased;

        if (snapshot.target - target).abs() > 1e-6 {
            // Mid-flight reversal: start smoothly from the current sampled progress
            // and scale duration proportionally to the remaining distance.
            let remaining_fraction = (target - sampled).abs().clamp(0.05, 1.0) as f64;
            let next_duration = duration.as_secs_f64() * remaining_fraction;
            state.update(cx, |s, _| {
                s.from = sampled;
                s.target = target;
                s.started_at_secs = now;
                s.duration_secs = next_duration;
                s.ease = ease;
            });
            window.request_animation_frame();
            return ArcPresenceSample {
                phase: if self.present {
                    PresencePhase::Entering
                } else {
                    PresencePhase::Exiting
                },
                progress: sampled,
                status: MotionStatus::Running,
            };
        }

        if (snapshot.from - snapshot.target).abs() <= 1e-6 || raw_t >= 1.0 {
            stable(self.present)
        } else {
            window.request_animation_frame();
            ArcPresenceSample {
                phase: if self.present {
                    PresencePhase::Entering
                } else {
                    PresencePhase::Exiting
                },
                progress: sampled,
                status: MotionStatus::Running,
            }
        }
    }
}

fn stable(present: bool) -> ArcPresenceSample {
    ArcPresenceSample {
        phase: if present {
            PresencePhase::Present
        } else {
            PresencePhase::Absent
        },
        progress: if present { 1.0 } else { 0.0 },
        status: MotionStatus::Finished,
    }
}

#[cfg(test)]
mod tests {
    use gpui_kit::{Context, IntoElement, Render, TestAppContext, div, test::TestWindowExt as _};

    use super::*;

    struct PresenceHost {
        present: bool,
        last: Option<ArcPresenceSample>,
    }

    impl Render for PresenceHost {
        fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
            let sample = ArcPresence::new(("host", "panel"), self.present).sample(window, cx);
            self.last = Some(sample);
            div()
        }
    }

    #[gpui_kit::test]
    fn presence_enters_exits_and_reverses_mid_flight(cx: &mut TestAppContext) {
        let (view, cx) = cx.add_window_view(|_, _| PresenceHost {
            present: true,
            last: None,
        });

        // Initial enter starts at 0.0 and advances to 1.0
        let first = cx.update(|window, cx| {
            window.render_frame(cx);
            view.read(cx).last.unwrap()
        });
        assert_eq!(first.phase, PresencePhase::Entering);
        assert!(first.should_render());

        cx.executor().advance_clock(Duration::from_millis(300));
        let settled = cx.update(|window, cx| {
            window.render_frame(cx);
            view.read(cx).last.unwrap()
        });
        assert_eq!(settled.phase, PresencePhase::Present);
        assert_eq!(settled.progress, 1.0);

        // Start exiting, then reopen mid-exit -> reverses smoothly from current progress
        view.update(cx, |v, cx| {
            v.present = false;
            cx.notify();
        });
        cx.update(|window, cx| window.render_frame(cx));
        cx.executor().advance_clock(Duration::from_millis(90));
        let mid_exit = cx.update(|window, cx| {
            window.render_frame(cx);
            view.read(cx).last.unwrap()
        });
        assert_eq!(mid_exit.phase, PresencePhase::Exiting);
        assert!(mid_exit.progress > 0.0 && mid_exit.progress < 1.0);

        view.update(cx, |v, cx| {
            v.present = true;
            cx.notify();
        });
        let reversed = cx.update(|window, cx| {
            window.render_frame(cx);
            view.read(cx).last.unwrap()
        });
        assert_eq!(reversed.phase, PresencePhase::Entering);
        assert!((reversed.progress - mid_exit.progress).abs() < 0.05);
    }
}