use gpui_kit::base::{self as base, Easing, Interpolate, ReduceMotionPreference, TransitionId};
use gpui_kit::{Animation, App, Hsla, Rgba, Window};
use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Curve {
ProductiveStandard,
ProductiveEntrance,
ProductiveExit,
ExpressiveStandard,
ExpressiveEntrance,
ExpressiveExit,
}
impl Curve {
pub const ALL: [Curve; 6] = [
Self::ProductiveStandard,
Self::ProductiveEntrance,
Self::ProductiveExit,
Self::ExpressiveStandard,
Self::ExpressiveEntrance,
Self::ExpressiveExit,
];
pub const fn points(self) -> (f32, f32, f32, f32) {
match self {
Self::ProductiveStandard => (0.2, 0., 0.38, 0.9),
Self::ProductiveEntrance => (0., 0., 0.38, 0.9),
Self::ProductiveExit => (0.2, 0., 1., 0.9),
Self::ExpressiveStandard => (0.4, 0.14, 0.3, 1.),
Self::ExpressiveEntrance => (0., 0., 0.3, 1.),
Self::ExpressiveExit => (0.4, 0.14, 1., 1.),
}
}
pub const fn label(self) -> &'static str {
match self {
Self::ProductiveStandard => "Productive standard",
Self::ProductiveEntrance => "Productive entrance",
Self::ProductiveExit => "Productive exit",
Self::ExpressiveStandard => "Expressive standard",
Self::ExpressiveEntrance => "Expressive entrance",
Self::ExpressiveExit => "Expressive exit",
}
}
pub fn ease(self, t: f32) -> f32 {
let (x1, y1, x2, y2) = self.points();
cubic_bezier_at(x1, y1, x2, y2, t)
}
pub fn ease_fn(self) -> impl Fn(f32) -> f32 + Copy + 'static {
move |t| self.ease(t)
}
pub fn easing(self) -> Easing {
let (x1, y1, x2, y2) = self.points();
Easing::cubic_bezier(x1, y1, x2, y2).expect("Carbon curves are valid")
}
}
pub fn cubic_bezier_at(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 {
let t = if t.is_nan() { 0. } else { t.clamp(0., 1.) };
if t == 0. || t == 1. {
return t;
}
let (cx, cy) = (3. * x1, 3. * y1);
let (bx, by) = (3. * (x2 - x1) - cx, 3. * (y2 - y1) - cy);
let (ax, ay) = (1. - cx - bx, 1. - cy - by);
let x = |s: f32| ((ax * s + bx) * s + cx) * s;
let dx = |s: f32| (3. * ax * s + 2. * bx) * s + cx;
let y = |s: f32| ((ay * s + by) * s + cy) * s;
let mut s = t;
for _ in 0..8 {
let err = x(s) - t;
if err.abs() < 1e-6 {
return y(s);
}
let d = dx(s);
if d.abs() < 1e-6 {
break;
}
s -= err / d;
}
let (mut lo, mut hi) = (0f32, 1f32);
s = t;
for _ in 0..40 {
let v = x(s);
if (v - t).abs() < 1e-6 {
break;
}
if v < t {
lo = s;
} else {
hi = s;
}
s = (lo + hi) / 2.;
}
y(s)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Speed {
Fast01,
Fast02,
Moderate01,
Moderate02,
Slow01,
Slow02,
}
impl Speed {
pub const ALL: [Speed; 6] = [
Self::Fast01,
Self::Fast02,
Self::Moderate01,
Self::Moderate02,
Self::Slow01,
Self::Slow02,
];
pub const fn millis(self) -> u64 {
match self {
Self::Fast01 => 70,
Self::Fast02 => 110,
Self::Moderate01 => 150,
Self::Moderate02 => 240,
Self::Slow01 => 400,
Self::Slow02 => 700,
}
}
pub const fn duration(self) -> Duration {
Duration::from_millis(self.millis())
}
pub const fn name(self) -> &'static str {
match self {
Self::Fast01 => "fast-01",
Self::Fast02 => "fast-02",
Self::Moderate01 => "moderate-01",
Self::Moderate02 => "moderate-02",
Self::Slow01 => "slow-01",
Self::Slow02 => "slow-02",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Motion {
pub curve: Curve,
pub speed: Speed,
pub spatial: bool,
}
impl Motion {
pub const HOVER: Motion = Motion::new(Curve::ProductiveEntrance, Speed::Fast01);
pub const TOGGLE: Motion = Motion::new(Curve::ProductiveStandard, Speed::Fast02).spatial(true);
pub const ENTER: Motion = Motion::new(Curve::ProductiveEntrance, Speed::Moderate02);
pub const EXIT: Motion = Motion::new(Curve::ProductiveExit, Speed::Fast02);
pub const fn new(curve: Curve, speed: Speed) -> Self {
Self {
curve,
speed,
spatial: false,
}
}
pub const fn spatial(mut self, spatial: bool) -> Self {
self.spatial = spatial;
self
}
pub fn transition(self) -> base::Transition {
base::Transition::new(self.speed.duration())
.easing(self.curve.easing())
.reduced_motion(if self.spatial {
base::ReducedMotion::Finish
} else {
base::ReducedMotion::Continue
})
}
pub fn animation(self) -> Animation {
Animation::new(self.speed.duration()).with_easing(self.curve.ease_fn())
}
}
pub fn animate<T>(
id: impl Into<TransitionId>,
target: T,
motion: Motion,
window: &mut Window,
cx: &mut App,
) -> T
where
T: Interpolate + PartialEq + 'static,
{
let sampled = base::transition_with_status(id, target.clone(), motion.transition(), window, cx);
settle(sampled, target)
}
fn settle<T>(sampled: base::MotionValue<T>, target: T) -> T {
match sampled.status {
base::MotionStatus::Idle | base::MotionStatus::Finished => target,
base::MotionStatus::Delayed | base::MotionStatus::Running => sampled.value,
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AnimatedColor(pub Rgba);
impl base::animation::Lerp for AnimatedColor {
fn lerp(&self, to: &Self, t: f32) -> Self {
let (a, b) = (self.0, to.0);
let alpha = a.a + (b.a - a.a) * t;
let channel = |x: f32, y: f32| {
let premultiplied = x * a.a + (y * b.a - x * a.a) * t;
if alpha > 0. { premultiplied / alpha } else { y }
};
AnimatedColor(Rgba {
r: channel(a.r, b.r),
g: channel(a.g, b.g),
b: channel(a.b, b.b),
a: alpha,
})
}
}
pub fn animate_color(
id: impl Into<TransitionId>,
target: impl Into<Hsla>,
motion: Motion,
window: &mut Window,
cx: &mut App,
) -> Hsla {
let target: Rgba = target.into().to_rgb();
animate(id, AnimatedColor(target), motion, window, cx)
.0
.into()
}
pub fn chevron_rotation(
id: impl Into<TransitionId>,
expanded: bool,
window: &mut Window,
cx: &mut App,
) -> f32 {
let target = if expanded { std::f32::consts::PI } else { 0. };
animate(id, target, Motion::TOGGLE, window, cx)
}
pub fn open_progress(
id: impl Into<TransitionId>,
open: bool,
window: &mut Window,
cx: &mut App,
) -> f32 {
let motion = if open { Motion::ENTER } else { Motion::EXIT };
animate(id, if open { 1f32 } else { 0. }, motion, window, cx)
}
pub fn reduced_motion(cx: &App) -> bool {
cx.reduce_motion()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ReducedMotion {
#[default]
System,
Reduce,
Allow,
}
pub fn set_reduced_motion(cx: &mut App, preference: ReducedMotion) {
base::set_reduce_motion_preference(
match preference {
ReducedMotion::System => ReduceMotionPreference::System,
ReducedMotion::Reduce => ReduceMotionPreference::Reduce,
ReducedMotion::Allow => ReduceMotionPreference::Allow,
},
cx,
);
cx.refresh_windows();
}
#[cfg(test)]
mod tests {
use super::*;
use gpui_kit::base::animation::Lerp as _;
#[test]
fn a_finished_transition_lands_exactly_on_its_target() {
let sampled = base::MotionValue {
value: 1. - Curve::ExpressiveExit.easing().sample(1.),
status: base::MotionStatus::Finished,
};
assert_eq!(settle(sampled, 0f32), 0.);
let idle = base::MotionValue {
value: 0.25f32,
status: base::MotionStatus::Idle,
};
assert_eq!(settle(idle, 0.5), 0.5);
let running = base::MotionValue {
value: 0.25f32,
status: base::MotionStatus::Running,
};
assert_eq!(settle(running, 1.), 0.25);
}
#[test]
fn curves_hit_their_endpoints_and_are_monotonic() {
for curve in Curve::ALL {
assert_eq!(curve.ease(0.), 0.);
assert_eq!(curve.ease(1.), 1.);
let mut last = 0.;
for i in 1..=100 {
let v = curve.ease(i as f32 / 100.);
assert!(v >= last - 1e-5, "{curve:?} not monotonic at {i}");
last = v;
}
}
}
#[test]
fn curves_match_css_reference_values() {
let close = |a: f32, b: f32| (a - b).abs() < 1e-3;
assert!(close(Curve::ProductiveEntrance.ease(0.5), 0.7301));
assert!(close(Curve::ProductiveStandard.ease(0.5), 0.6848));
assert!(close(Curve::ProductiveExit.ease(0.5), 0.3848));
assert!(close(Curve::ExpressiveEntrance.ease(0.5), 0.8055));
assert!(close(cubic_bezier_at(0.25, 0.1, 0.25, 1., 0.5), 0.8024));
assert!(close(cubic_bezier_at(0., 0., 1., 1., 0.3), 0.3));
}
#[test]
fn our_bezier_agrees_with_base_easing() {
for curve in Curve::ALL {
let easing = curve.easing();
for i in 0..=20 {
let t = i as f32 / 20.;
assert!(
(easing.sample(t) - curve.ease(t)).abs() < 2e-3,
"{curve:?} at {t}"
);
}
}
}
#[test]
fn duration_tokens() {
let ms: Vec<u64> = Speed::ALL.iter().map(|s| s.millis()).collect();
assert_eq!(ms, [70, 110, 150, 240, 400, 700]);
assert_eq!(Motion::HOVER.speed.duration(), Duration::from_millis(70));
}
#[test]
fn color_interpolation_is_premultiplied() {
let clear = AnimatedColor(Rgba {
r: 0.,
g: 0.,
b: 0.,
a: 0.,
});
let gray = AnimatedColor(Rgba {
r: 0.55,
g: 0.55,
b: 0.55,
a: 0.12,
});
let mid = clear.lerp(&gray, 0.5);
assert!((mid.0.r - 0.55).abs() < 1e-5, "no darkening through black");
assert!((mid.0.a - 0.06).abs() < 1e-5);
}
}