Skip to main content

gpui_base/
animation.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    Animation, AnimationExt, ElementId, Hsla, IntoElement, Pixels, Point, Styled, hsla, point,
5    prelude::FluentBuilder, px,
6};
7use smallvec::SmallVec;
8
9/// A cubic bezier function like CSS `cubic-bezier`.
10///
11/// Builder:
12///
13/// https://cubic-bezier.com
14pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 {
15    // Polynomial form of the unit bezier, where p0 = (0, 0) and p3 = (1, 1).
16    let (cx, cy) = (3.0 * x1, 3.0 * y1);
17    let (bx, by) = (3.0 * (x2 - x1) - cx, 3.0 * (y2 - y1) - cy);
18    let (ax, ay) = (1.0 - cx - bx, 1.0 - cy - by);
19    let sample_x = move |t: f32| ((ax * t + bx) * t + cx) * t;
20    let sample_y = move |t: f32| ((ay * t + by) * t + cy) * t;
21    let slope_x = move |t: f32| (3.0 * ax * t + 2.0 * bx) * t + cx;
22
23    // Solve `x(s) = t` for the curve parameter `s`.
24    let solve_s = move |t: f32| {
25        let mut s = t;
26        for _ in 0..8 {
27            let error = sample_x(s) - t;
28            if error.abs() < 1e-6 {
29                return s;
30            }
31            let slope = slope_x(s);
32            if slope.abs() < 1e-6 {
33                break;
34            }
35            s = (s - error / slope).clamp(0.0, 1.0);
36        }
37
38        let (mut low, mut high) = (0.0, 1.0);
39        let mut s = t;
40        for _ in 0..32 {
41            let x = sample_x(s);
42            if (x - t).abs() < 1e-6 {
43                break;
44            }
45            if x < t {
46                low = s;
47            } else {
48                high = s;
49            }
50            s = (low + high) / 2.0;
51        }
52        s
53    };
54
55    move |t: f32| {
56        let t = t.clamp(0.0, 1.0);
57        // `t` is elapsed progress along x, not the curve parameter: solve
58        // `x(s) = t` before sampling y, otherwise the curve reads much slower
59        // than the same control points do in CSS. GPUI asserts easing deltas
60        // stay within [0, 1], so clamp away solver and rounding error.
61        sample_y(solve_s(t)).clamp(0.0, 1.0)
62    }
63}
64
65// ── Easing presets ──────────────────────────────────────────────────────────
66
67/// Cubic ease-out — fast start, slow end. Good for enter animations.
68pub fn ease_out_cubic(t: f32) -> f32 {
69    let t = t.clamp(0.0, 1.0);
70    1.0 - (1.0 - t).powi(3)
71}
72
73/// Cubic ease-in — slow start, fast end. Good for exit animations.
74pub fn ease_in_cubic(t: f32) -> f32 {
75    let t = t.clamp(0.0, 1.0);
76    t * t * t
77}
78
79/// Cubic ease-in-out — slow start and end. Good for position transitions.
80pub fn ease_in_out_cubic(t: f32) -> f32 {
81    let t = t.clamp(0.0, 1.0);
82    if t < 0.5 {
83        4.0 * t * t * t
84    } else {
85        1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
86    }
87}
88
89// ── Lerp trait ──────────────────────────────────────────────────────────────
90
91/// Trait for types that support linear interpolation.
92pub trait Lerp: Clone {
93    fn lerp(&self, target: &Self, t: f32) -> Self;
94}
95
96impl Lerp for f32 {
97    fn lerp(&self, target: &Self, t: f32) -> Self {
98        self + (target - self) * t
99    }
100}
101
102impl Lerp for Pixels {
103    fn lerp(&self, target: &Self, t: f32) -> Self {
104        let a: f32 = (*self).into();
105        let b: f32 = (*target).into();
106        px(a + (b - a) * t)
107    }
108}
109
110impl Lerp for Point<Pixels> {
111    fn lerp(&self, target: &Self, t: f32) -> Self {
112        point(
113            Lerp::lerp(&self.x, &target.x, t),
114            Lerp::lerp(&self.y, &target.y, t),
115        )
116    }
117}
118
119impl Lerp for Hsla {
120    /// Interpolate each channel linearly. Intended for transitions between
121    /// near-grayscale UI colors (e.g. text colors), where hue interpolation is
122    /// irrelevant.
123    fn lerp(&self, target: &Self, t: f32) -> Self {
124        hsla(
125            (self.color.hue.into_degrees() / 360.)
126                .lerp(&(target.color.hue.into_degrees() / 360.), t),
127            self.color.saturation.lerp(&target.color.saturation, t),
128            self.color.lightness.lerp(&target.color.lightness, t),
129            self.alpha.lerp(&target.alpha, t),
130        )
131    }
132}
133
134// ── Transition combinator ───────────────────────────────────────────────────
135
136/// A composable transition that applies concrete fade, slide, and size effects
137/// to an element.
138///
139/// This is distinct from [`crate::motion::Transition`], which is a timing
140/// policy for a caller-chosen value and never picks a visual property. Prefer
141/// `motion` for new code.
142///
143/// # Example
144///
145/// ```ignore
146/// EffectTransition::new(Duration::from_millis(150))
147///     .ease(ease_out_cubic)
148///     .slide_y(px(-4.), px(0.))
149///     .fade(0.0, 1.0)
150///     .apply(element, "enter-anim")
151/// ```
152#[derive(Clone)]
153pub struct EffectTransition {
154    pub duration: Duration,
155    easing: Rc<dyn Fn(f32) -> f32>,
156    effects: SmallVec<[TransitionEffect; 2]>,
157}
158
159#[derive(Clone, Copy)]
160enum TransitionEffect {
161    SlideY(Pixels, Pixels),
162    SlideX(Pixels, Pixels),
163    Fade(f32, f32),
164    Width(Pixels, Pixels),
165    Height(Pixels, Pixels),
166}
167
168impl EffectTransition {
169    pub fn new(duration: Duration) -> Self {
170        Self {
171            duration,
172            easing: Rc::new(ease_out_cubic),
173            effects: SmallVec::new(),
174        }
175    }
176
177    /// Set the easing function.
178    pub fn ease(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
179        self.easing = Rc::new(easing);
180        self
181    }
182
183    /// Animate vertical offset from `from` to `to`.
184    pub fn slide_y(mut self, from: Pixels, to: Pixels) -> Self {
185        self.effects.push(TransitionEffect::SlideY(from, to));
186        self
187    }
188
189    /// Animate horizontal offset from `from` to `to`.
190    pub fn slide_x(mut self, from: Pixels, to: Pixels) -> Self {
191        self.effects.push(TransitionEffect::SlideX(from, to));
192        self
193    }
194
195    /// Animate opacity from `from` to `to`.
196    pub fn fade(mut self, from: f32, to: f32) -> Self {
197        self.effects.push(TransitionEffect::Fade(from, to));
198        self
199    }
200
201    /// Animate width from `from` to `to`.
202    pub fn width(mut self, from: Pixels, to: Pixels) -> Self {
203        self.effects.push(TransitionEffect::Width(from, to));
204        self
205    }
206
207    /// Animate height from `from` to `to`.
208    pub fn height(mut self, from: Pixels, to: Pixels) -> Self {
209        self.effects.push(TransitionEffect::Height(from, to));
210        self
211    }
212
213    /// Apply this transition to a Styled element, returning an AnimationElement.
214    pub fn apply<E: IntoElement + Styled + 'static>(
215        self,
216        element: E,
217        id: impl Into<ElementId>,
218    ) -> gpui::AnimationElement<E> {
219        let animation = Animation::new(self.duration).with_easing({
220            let easing = self.easing.clone();
221            move |t| easing(t)
222        });
223        let effects = self.effects;
224        element.with_animation(id, animation, move |el, delta| {
225            let mut el = el;
226            for effect in &effects {
227                match effect {
228                    TransitionEffect::SlideY(from, to) => {
229                        el = el.top(Lerp::lerp(from, to, delta));
230                    }
231                    TransitionEffect::SlideX(from, to) => {
232                        el = el.left(Lerp::lerp(from, to, delta));
233                    }
234                    TransitionEffect::Fade(from, to) => {
235                        el = el.opacity(Lerp::lerp(from, to, delta));
236                    }
237                    TransitionEffect::Width(from, to) => {
238                        el = el.w(Lerp::lerp(from, to, delta));
239                    }
240                    TransitionEffect::Height(from, to) => {
241                        el = el.h(Lerp::lerp(from, to, delta));
242                    }
243                }
244            }
245            el
246        })
247    }
248}
249
250impl FluentBuilder for EffectTransition {}
251
252/// Former name of [`EffectTransition`].
253///
254/// Renamed because `motion::Transition` and this type were two different
255/// concepts sharing one name.
256#[deprecated(since = "0.5.2", note = "renamed to `EffectTransition`")]
257pub type Transition = EffectTransition;
258
259#[cfg(test)]
260mod tests {
261    use super::cubic_bezier;
262
263    #[test]
264    fn cubic_bezier_matches_engine_published_values() {
265        // Reference values sampled from the CSS `ease` curve.
266        let ease = cubic_bezier(0.25, 0.1, 0.25, 1.);
267        for (t, expected) in [
268            (0.0, 0.0),
269            (0.2, 0.295),
270            (0.5, 0.802),
271            (0.8, 0.976),
272            (1.0, 1.0),
273        ] {
274            assert!(
275                (ease(t) - expected).abs() < 1e-3,
276                "ease({t}) = {}, expected {expected}",
277                ease(t)
278            );
279        }
280
281        // Chromium's CubicBezier(0.25, 0, 0.75, 1) expectations, from
282        // ui/gfx/geometry/cubic_bezier_unittest.cc (epsilon 0.00015 there;
283        // widened for our f32 arithmetic).
284        let curve = cubic_bezier(0.25, 0., 0.75, 1.);
285        for (t, expected) in [
286            (0.05, 0.01136),
287            (0.1, 0.03978),
288            (0.15, 0.07978),
289            (0.2, 0.12803),
290            (0.25, 0.18235),
291            (0.3, 0.24115),
292            (0.35, 0.30323),
293            (0.4, 0.36761),
294            (0.45, 0.43345),
295            (0.5, 0.5),
296            (0.6, 0.63238),
297            (0.65, 0.69676),
298            (0.7, 0.75884),
299            (0.75, 0.81764),
300            (0.8, 0.87196),
301            (0.85, 0.92021),
302            (0.9, 0.96021),
303            (0.95, 0.98863),
304        ] {
305            assert!(
306                (curve(t) - expected).abs() < 3e-4,
307                "curve({t}) = {}, Chromium says {expected}",
308                curve(t)
309            );
310        }
311    }
312
313    #[test]
314    fn cubic_bezier_with_thirds_x_maps_time_identically() {
315        // x1 = 1/3, x2 = 2/3 collapse the x solve to the identity, making the
316        // output the plain y polynomial; Dialog relies on this to keep the
317        // trajectory it was tuned with before `cubic_bezier` solved for x.
318        let ease = cubic_bezier(1. / 3., 0.72, 2. / 3., 1.);
319        for step in 0..=100 {
320            let t = step as f32 / 100.;
321            let one_t = 1. - t;
322            let expected = 3. * 0.72 * one_t * one_t * t + 3. * one_t * t * t + t * t * t;
323            assert!(
324                (ease(t) - expected).abs() < 1e-4,
325                "ease({t}) = {}, expected {expected}",
326                ease(t)
327            );
328        }
329    }
330
331    #[test]
332    fn cubic_bezier_matches_the_css_definition() {
333        // Reference solver written straight off the CSS Easing Functions
334        // definition — solve `x(s) = t` by bisection in f64, then sample
335        // `y(s)` — independent of the production Newton solver.
336        fn css_reference(x1: f64, y1: f64, x2: f64, y2: f64, t: f64) -> f64 {
337            let sample = |p1: f64, p2: f64, s: f64| {
338                3. * p1 * (1. - s) * (1. - s) * s + 3. * p2 * (1. - s) * s * s + s * s * s
339            };
340            let (mut low, mut high) = (0f64, 1f64);
341            for _ in 0..64 {
342                let mid = (low + high) / 2.;
343                if sample(x1, x2, mid) < t {
344                    low = mid;
345                } else {
346                    high = mid;
347                }
348            }
349            sample(y1, y2, (low + high) / 2.)
350        }
351
352        let curves = [
353            // The runtime curves in this repo.
354            (0.25, 0.1, 0.25, 1.),
355            (1. / 3., 0.72, 2. / 3., 1.),
356            // CSS keyword curves.
357            (0.42, 0., 1., 1.),
358            (0., 0., 0.58, 1.),
359            (0.42, 0., 0.58, 1.),
360            (0., 0., 1., 1.),
361            // Degenerate x slopes: zero at s = 0.5, 0, and 1, forcing the
362            // Newton solve to fall back to bisection.
363            (1., 0., 0., 1.),
364            (0., 0., 0., 1.),
365            (1., 0.5, 1., 0.5),
366        ];
367        for (x1, y1, x2, y2) in curves {
368            let ease = cubic_bezier(x1, y1, x2, y2);
369            for step in 0..=1000 {
370                let t = step as f32 / 1000.;
371                let y = ease(t);
372                let expected =
373                    css_reference(x1 as f64, y1 as f64, x2 as f64, y2 as f64, t as f64) as f32;
374                assert!(
375                    (y - expected).abs() < 5e-4,
376                    "cubic_bezier({x1}, {y1}, {x2}, {y2})({t}) = {y}, CSS = {expected}"
377                );
378                // GPUI panics when an easing delta leaves [0, 1].
379                assert!((0.0..=1.0).contains(&y), "ease({t}) = {y} out of range");
380            }
381        }
382    }
383
384    #[test]
385    fn cubic_bezier_is_monotonic_and_clamped() {
386        let ease = cubic_bezier(0.32, 0.72, 0., 1.);
387        assert_eq!(ease(-1.), 0.);
388        assert_eq!(ease(2.), 1.);
389
390        let mut previous = 0.;
391        for step in 0..=100 {
392            let current = ease(step as f32 / 100.);
393            assert!(current >= previous - 1e-4, "not monotonic at {step}");
394            previous = current;
395        }
396    }
397}