Skip to main content

fc_ui/capabilities/motion/
animations.rs

1//! # Animation Utilities and Presets
2//!
3//! Professional animation system providing smooth, polished easing functions and reusable
4//! animation configurations for desktop application interfaces.
5//! ## Features
6//!
7//! - **Easing Functions**: Mathematical easing curves for natural motion
8//! - **Duration Presets**: Standardized timing values following UI guidelines
9//! - **Animation Presets**: Ready-to-use animations for common interactions
10//! - **Spring Physics**: Realistic bouncy animations with configurable parameters
11//! - **Performance**: Optimized calculations with minimal runtime overhead
12//!
13//! ## Easing Categories
14//!
15//! - **Linear**: Constant velocity (rarely natural for UI)
16//! - **Quadratic/Cubic/Quartic**: Smooth acceleration/deceleration
17//! - **Exponential**: Dramatic acceleration (good for entrances)
18//! - **Spring**: Natural bouncy motion with physics simulation
19//! - **Back**: Slight overshoot for emphasis (subtle bounce effect)
20//!
21//! ## Usage Examples
22//!
23//! ### Basic Animation
24//! ```rust,ignore
25//! use fc_ui::animations::*;
26//!
27//! // Fade in with smooth easing
28//! div()
29//!     .with_animation(
30//!         "fade-in",
31//!         fade_in(Duration::from_millis(300)),
32//!         |el, delta| el.opacity(delta)
33//!     )
34//! ```
35//!
36//! ### Spring Animation
37//! ```rust,ignore
38//! // Natural slide with bounce
39//! div()
40//!     .with_animation(
41//!         "slide-spring",
42//!         spring_slide(Duration::from_millis(400)),
43//!         |el, delta| el.ml(px(-100.0 * (1.0 - delta)))
44//!     )
45//! ```
46//!
47//! ### Preset Usage
48//! ```rust,ignore
49//! // Use predefined animations
50//! div().with_animation(
51//!     "bounce",
52//!     presets::bounce_in(),
53//!     |el, delta| el.scale(delta)
54//! )
55//! ```
56//!
57//! ## Design Decisions
58//!
59//! - **Performance First**: All calculations are lightweight and cache-friendly
60//! - **Natural Motion**: Easing curves based on real-world physics observations
61//! - **Consistency**: Standardized durations and easing across the library
62//! - **Extensibility**: Easy to add custom easing functions and presets
63//! - **GPUI Integration**: Seamless integration with GPUI's animation system
64//!
65
66use gpui::*;
67use smallvec::SmallVec;
68use std::time::Duration;
69
70/// Standard animation durations following modern UI guidelines
71pub mod durations {
72    use std::time::Duration;
73
74    /// Ultra fast (100ms) - for micro-interactions
75    pub const ULTRA_FAST: Duration = Duration::from_millis(100);
76
77    /// Very fast (150ms) - for subtle state changes
78    pub const FASTEST: Duration = Duration::from_millis(150);
79
80    /// Fast (200ms) - for quick transitions
81    pub const FAST: Duration = Duration::from_millis(200);
82
83    /// Normal (300ms) - default for most animations
84    pub const NORMAL: Duration = Duration::from_millis(300);
85
86    /// Slow (400ms) - for emphasis
87    pub const SLOW: Duration = Duration::from_millis(400);
88
89    /// Very slow (500ms) - for dramatic effects
90    pub const SLOWEST: Duration = Duration::from_millis(500);
91
92    /// Extra slow (600ms) - for very dramatic effects
93    pub const EXTRA_SLOW: Duration = Duration::from_millis(600);
94}
95
96/// Professional easing functions for smooth animations
97/// Based on CSS cubic-bezier curves and spring physics
98pub mod easings {
99    /// Linear easing (no acceleration)
100    pub fn linear(t: f32) -> f32 {
101        t
102    }
103
104    /// Ease in quad - starts slow, accelerates
105    pub fn ease_in_quad(t: f32) -> f32 {
106        t * t
107    }
108
109    /// Ease out quad - starts fast, decelerates
110    pub fn ease_out_quad(t: f32) -> f32 {
111        t * (2.0 - t)
112    }
113
114    /// Ease in-out quad - smooth acceleration and deceleration
115    pub fn ease_in_out_quad(t: f32) -> f32 {
116        if t < 0.5 {
117            2.0 * t * t
118        } else {
119            -1.0 + (4.0 - 2.0 * t) * t
120        }
121    }
122
123    /// Ease in cubic - stronger acceleration
124    pub fn ease_in_cubic(t: f32) -> f32 {
125        t * t * t
126    }
127
128    /// Ease out cubic - stronger deceleration (most natural feeling)
129    pub fn ease_out_cubic(t: f32) -> f32 {
130        let t = t - 1.0;
131        t * t * t + 1.0
132    }
133
134    /// Ease in-out cubic - smooth and professional (recommended default)
135    pub fn ease_in_out_cubic(t: f32) -> f32 {
136        if t < 0.5 {
137            4.0 * t * t * t
138        } else {
139            let t = 2.0 * t - 2.0;
140            1.0 + t * t * t / 2.0
141        }
142    }
143
144    /// Ease in quart - very strong acceleration
145    pub fn ease_in_quart(t: f32) -> f32 {
146        t * t * t * t
147    }
148
149    /// Ease out quart - very smooth deceleration
150    pub fn ease_out_quart(t: f32) -> f32 {
151        let t = t - 1.0;
152        1.0 - t * t * t * t
153    }
154
155    /// Ease in-out quart - very smooth both ways
156    pub fn ease_in_out_quart(t: f32) -> f32 {
157        if t < 0.5 {
158            8.0 * t * t * t * t
159        } else {
160            let t = t - 1.0;
161            1.0 - 8.0 * t * t * t * t
162        }
163    }
164
165    /// Ease out expo - dramatic deceleration
166    pub fn ease_out_expo(t: f32) -> f32 {
167        if t >= 1.0 {
168            1.0
169        } else {
170            1.0 - 2_f32.powf(-10.0 * t)
171        }
172    }
173
174    /// Ease in-out expo - dramatic both ways
175    pub fn ease_in_out_expo(t: f32) -> f32 {
176        if t == 0.0 {
177            0.0
178        } else if t >= 1.0 {
179            1.0
180        } else if t < 0.5 {
181            2_f32.powf(20.0 * t - 10.0) / 2.0
182        } else {
183            (2.0 - 2_f32.powf(-20.0 * t + 10.0)) / 2.0
184        }
185    }
186
187    /// Spring easing - natural bouncy effect
188    ///
189    /// Starts at 0 and settles at 1 with a decaying oscillation. The output is
190    /// intentionally not clamped so the bounce can overshoot 1.0, matching
191    /// GPUI's `Animation::with_easing` semantics.
192    pub fn spring(t: f32) -> f32 {
193        if t >= 1.0 {
194            return 1.0;
195        }
196        let damping = 0.7;
197        let frequency = 1.5;
198        let decay = (-damping * t * 10.0).exp();
199        let oscillation = (frequency * t * std::f32::consts::PI * 2.0).cos();
200        1.0 - decay * oscillation
201    }
202
203    /// Elastic easing - more pronounced spring effect
204    ///
205    /// The output is intentionally not clamped so the elastic wobble can
206    /// overshoot 1.0, matching GPUI's `Animation::with_easing` semantics.
207    pub fn elastic(t: f32) -> f32 {
208        if t == 0.0 {
209            return 0.0;
210        }
211        if t >= 1.0 {
212            return 1.0;
213        }
214        let p = 0.3;
215        let s = p / 4.0;
216        let t_adj = t - 1.0;
217        1.0 + (2_f32.powf(10.0 * t_adj)) * ((t_adj - s) * (2.0 * std::f32::consts::PI) / p).sin()
218    }
219
220    /// Smooth spring - subtle spring effect (recommended for UI)
221    ///
222    /// The output is intentionally not clamped so the subtle spring can
223    /// overshoot 1.0, matching GPUI's `Animation::with_easing` semantics.
224    pub fn smooth_spring(t: f32) -> f32 {
225        if t >= 1.0 {
226            return 1.0;
227        }
228        let damping = 0.9; // Increased damping for smoother effect
229        let frequency = 1.0;
230        let decay = (-damping * t * 10.0).exp();
231        let oscillation = (frequency * t * std::f32::consts::PI * 2.0).sin();
232        t + decay * oscillation * 0.1 // Very subtle spring
233    }
234
235    /// Back easing - slight overshoot for emphasis
236    ///
237    /// `c1` is deliberately smaller than the canonical 1.70158 for a subtle
238    /// overshoot. The output is not clamped, matching GPUI's
239    /// `Animation::with_easing` semantics.
240    pub fn ease_out_back(t: f32) -> f32 {
241        if t >= 1.0 {
242            return 1.0;
243        }
244        let c1 = 1.2;
245        let c3 = c1 + 1.0;
246        let t_adj = t - 1.0;
247        1.0 + c3 * t_adj * t_adj * t_adj + c1 * t_adj * t_adj
248    }
249
250    pub fn ease_in_expo(t: f32) -> f32 {
251        if t == 0.0 {
252            0.0
253        } else {
254            2_f32.powf(10.0 * t - 10.0)
255        }
256    }
257
258    pub fn ease_in_circ(t: f32) -> f32 {
259        1.0 - (1.0 - t * t).sqrt()
260    }
261
262    pub fn ease_out_circ(t: f32) -> f32 {
263        let t = t - 1.0;
264        (1.0 - t * t).sqrt()
265    }
266
267    pub fn ease_in_out_circ(t: f32) -> f32 {
268        if t < 0.5 {
269            (1.0 - (1.0 - (2.0 * t).powi(2)).sqrt()) / 2.0
270        } else {
271            ((1.0 - (-2.0 * t + 2.0).powi(2)).sqrt() + 1.0) / 2.0
272        }
273    }
274
275    pub fn ease_in_back(t: f32) -> f32 {
276        let c1 = 1.70158;
277        let c3 = c1 + 1.0;
278        (c3 * t * t * t - c1 * t * t).max(0.0)
279    }
280
281    pub fn ease_in_out_back(t: f32) -> f32 {
282        let c1 = 1.70158;
283        let c2 = c1 * 1.525;
284        if t < 0.5 {
285            ((2.0 * t).powi(2) * ((c2 + 1.0) * 2.0 * t - c2)) / 2.0
286        } else {
287            let result =
288                ((2.0 * t - 2.0).powi(2) * ((c2 + 1.0) * (t * 2.0 - 2.0) + c2) + 2.0) / 2.0;
289            result.clamp(0.0, 1.0)
290        }
291    }
292
293    pub fn ease_in_elastic(t: f32) -> f32 {
294        if t == 0.0 {
295            return 0.0;
296        }
297        if t >= 1.0 {
298            return 1.0;
299        }
300        let c4 = (2.0 * std::f32::consts::PI) / 3.0;
301        let result = -(2_f32.powf(10.0 * t - 10.0) * ((t * 10.0 - 10.75) * c4).sin());
302        result.clamp(0.0, 1.0)
303    }
304
305    pub fn ease_out_elastic(t: f32) -> f32 {
306        if t == 0.0 {
307            return 0.0;
308        }
309        if t >= 1.0 {
310            return 1.0;
311        }
312        let c4 = (2.0 * std::f32::consts::PI) / 3.0;
313        let result = 2_f32.powf(-10.0 * t) * ((t * 10.0 - 0.75) * c4).sin() + 1.0;
314        result.clamp(0.0, 1.0)
315    }
316
317    pub fn ease_in_quint(t: f32) -> f32 {
318        t * t * t * t * t
319    }
320
321    pub fn ease_out_quint(t: f32) -> f32 {
322        let t = t - 1.0;
323        1.0 + t * t * t * t * t
324    }
325
326    pub fn ease_in_out_quint(t: f32) -> f32 {
327        if t < 0.5 {
328            16.0 * t * t * t * t * t
329        } else {
330            let t = 2.0 * t - 2.0;
331            1.0 + t * t * t * t * t / 2.0
332        }
333    }
334
335    pub fn steps(n: u32) -> impl Fn(f32) -> f32 {
336        move |t: f32| {
337            let n = n.max(1) as f32;
338            (t * n).floor() / n
339        }
340    }
341
342    pub fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32) -> impl Fn(f32) -> f32 {
343        move |t: f32| {
344            if t <= 0.0 {
345                return 0.0;
346            }
347            if t >= 1.0 {
348                return 1.0;
349            }
350            let mut low = 0.0_f32;
351            let mut high = 1.0_f32;
352            let mut mid;
353            for _ in 0..20 {
354                mid = (low + high) / 2.0;
355                let x = cubic_bezier_sample(mid, x1, x2);
356                if (x - t).abs() < 0.0001 {
357                    return cubic_bezier_sample(mid, y1, y2);
358                }
359                if x < t {
360                    low = mid;
361                } else {
362                    high = mid;
363                }
364            }
365            cubic_bezier_sample((low + high) / 2.0, y1, y2)
366        }
367    }
368
369    fn cubic_bezier_sample(t: f32, p1: f32, p2: f32) -> f32 {
370        let t2 = t * t;
371        let t3 = t2 * t;
372        3.0 * (1.0 - t) * (1.0 - t) * t * p1 + 3.0 * (1.0 - t) * t2 * p2 + t3
373    }
374
375    pub fn smooth() -> impl Fn(f32) -> f32 {
376        ease_in_out_cubic
377    }
378
379    pub fn snappy() -> impl Fn(f32) -> f32 {
380        ease_out_back
381    }
382}
383
384/// Creates a smooth fade-in animation
385///
386/// Uses cubic easing for the most natural fade effect
387pub fn fade_in(duration: Duration) -> Animation {
388    Animation::new(duration).with_easing(easings::ease_out_cubic)
389}
390
391/// Creates a smooth fade-out animation
392pub fn fade_out(duration: Duration) -> Animation {
393    Animation::new(duration).with_easing(easings::ease_in_cubic)
394}
395
396/// Creates a smooth slide animation
397///
398/// Best for sliding panels, drawers, and menus
399pub fn slide_animation(duration: Duration) -> Animation {
400    Animation::new(duration).with_easing(easings::ease_out_cubic)
401}
402
403/// Creates a spring-based slide animation
404///
405/// Natural feeling slide with subtle bounce
406pub fn spring_slide(duration: Duration) -> Animation {
407    Animation::new(duration).with_easing(easings::smooth_spring)
408}
409
410/// Creates a scale animation with back easing
411///
412/// Scales with a slight overshoot for emphasis
413pub fn scale_animation(duration: Duration) -> Animation {
414    Animation::new(duration).with_easing(easings::ease_out_back)
415}
416
417/// Creates a smooth scale animation without overshoot
418pub fn scale_smooth(duration: Duration) -> Animation {
419    Animation::new(duration).with_easing(easings::ease_out_cubic)
420}
421
422/// Creates a rotation animation
423pub fn rotate_animation(duration: Duration) -> Animation {
424    Animation::new(duration).with_easing(easings::linear)
425}
426
427/// Creates a smooth, professional pulse animation
428///
429/// Uses sine wave for natural breathing effect
430pub fn pulse_animation(duration: Duration) -> Animation {
431    Animation::new(duration).with_easing(easings::linear)
432}
433
434/// Creates a shake animation (horizontal movement)
435///
436/// Uses elastic easing for realistic shake
437pub fn shake_animation(duration: Duration) -> Animation {
438    Animation::new(duration).with_easing(easings::ease_out_quad)
439}
440
441/// Creates a bounce animation with spring physics
442pub fn bounce_animation(duration: Duration) -> Animation {
443    Animation::new(duration).with_easing(easings::spring)
444}
445
446/// Creates a smooth bounce without overshoot
447pub fn bounce_smooth(duration: Duration) -> Animation {
448    Animation::new(duration).with_easing(easings::ease_out_quart)
449}
450
451/// Creates an elastic spring animation
452pub fn spring_animation(duration: Duration) -> Animation {
453    Animation::new(duration).with_easing(easings::smooth_spring)
454}
455
456/// Pre-configured animation presets with optimal settings
457pub mod presets {
458    use crate::capabilities::motion::animations::durations;
459    use crate::capabilities::motion::animations::{
460        bounce_animation, bounce_smooth, fade_in, fade_out, pulse_animation, rotate_animation,
461        scale_animation, scale_smooth, shake_animation, slide_animation, spring_animation,
462        spring_slide,
463    };
464    use gpui::Animation;
465    use std::time::Duration;
466
467    // Fade animations
468    /// Ultra-quick fade in (100ms) - for tooltips
469    pub fn fade_in_ultra_quick() -> Animation {
470        fade_in(durations::ULTRA_FAST)
471    }
472
473    /// Quick fade in (200ms) - for fast transitions
474    pub fn fade_in_quick() -> Animation {
475        fade_in(durations::FAST)
476    }
477
478    /// Normal fade in (300ms) - standard UI transition
479    pub fn fade_in_normal() -> Animation {
480        fade_in(durations::NORMAL)
481    }
482
483    /// Slow fade in (400ms) - for emphasis
484    pub fn fade_in_slow() -> Animation {
485        fade_in(durations::SLOW)
486    }
487
488    /// Quick fade out (200ms)
489    pub fn fade_out_quick() -> Animation {
490        fade_out(durations::FAST)
491    }
492
493    /// Normal fade out (300ms)
494    pub fn fade_out_normal() -> Animation {
495        fade_out(durations::NORMAL)
496    }
497
498    // Slide animations with improved easing
499    /// Slide in from top with smooth easing
500    pub fn slide_in_top() -> Animation {
501        slide_animation(durations::NORMAL)
502    }
503
504    /// Slide in from bottom with smooth easing
505    pub fn slide_in_bottom() -> Animation {
506        slide_animation(durations::NORMAL)
507    }
508
509    /// Slide in from left with smooth easing
510    pub fn slide_in_left() -> Animation {
511        slide_animation(durations::NORMAL)
512    }
513
514    /// Slide in from right with smooth easing
515    pub fn slide_in_right() -> Animation {
516        slide_animation(durations::NORMAL)
517    }
518
519    /// Spring slide from left - natural feeling
520    pub fn spring_slide_left() -> Animation {
521        spring_slide(durations::SLOW)
522    }
523
524    /// Spring slide from right - natural feeling
525    pub fn spring_slide_right() -> Animation {
526        spring_slide(durations::SLOW)
527    }
528
529    // Scale animations
530    /// Scale up with back easing (slight overshoot)
531    pub fn scale_up() -> Animation {
532        scale_animation(durations::FAST)
533    }
534
535    /// Scale down with back easing
536    pub fn scale_down() -> Animation {
537        scale_animation(durations::FAST)
538    }
539
540    /// Smooth scale up (no overshoot)
541    pub fn scale_up_smooth() -> Animation {
542        scale_smooth(durations::FAST)
543    }
544
545    /// Smooth scale down (no overshoot)
546    pub fn scale_down_smooth() -> Animation {
547        scale_smooth(durations::FAST)
548    }
549
550    // Rotation animations
551    /// Continuous spin (2 seconds per rotation)
552    pub fn spin() -> Animation {
553        rotate_animation(Duration::from_secs(2)).repeat()
554    }
555
556    /// Fast spin (1 second per rotation)
557    pub fn spin_fast() -> Animation {
558        rotate_animation(Duration::from_secs(1)).repeat()
559    }
560
561    /// Slow spin (3 seconds per rotation) - for loading indicators
562    pub fn spin_slow() -> Animation {
563        rotate_animation(Duration::from_secs(3)).repeat()
564    }
565
566    // Pulse animations - improved smoothness
567    /// Smooth pulse effect (1 second cycle)
568    pub fn pulse() -> Animation {
569        pulse_animation(Duration::from_secs(1)).repeat()
570    }
571
572    /// Fast pulse (600ms cycle) - for urgent notifications
573    pub fn pulse_fast() -> Animation {
574        pulse_animation(durations::EXTRA_SLOW).repeat()
575    }
576
577    /// Slow pulse (1.5 second cycle) - for subtle breathing effect
578    pub fn pulse_slow() -> Animation {
579        pulse_animation(Duration::from_millis(1500)).repeat()
580    }
581
582    // Interactive animations
583    /// Shake effect (error indication)
584    pub fn shake() -> Animation {
585        shake_animation(durations::FAST)
586    }
587
588    /// Strong shake (critical error)
589    pub fn shake_strong() -> Animation {
590        shake_animation(durations::NORMAL)
591    }
592
593    // Bounce animations
594    /// Bounce in effect with spring physics
595    pub fn bounce_in() -> Animation {
596        bounce_animation(durations::SLOW)
597    }
598
599    /// Smooth bounce (no overshoot)
600    pub fn bounce_smooth_preset() -> Animation {
601        bounce_smooth(durations::NORMAL)
602    }
603
604    // Spring animations
605    /// Spring effect (natural feeling)
606    pub fn spring() -> Animation {
607        spring_animation(durations::SLOW)
608    }
609
610    /// Quick spring
611    pub fn spring_quick() -> Animation {
612        spring_animation(durations::NORMAL)
613    }
614}
615
616/// Animation state management helper
617#[derive(Clone, Copy, Debug, PartialEq, Default)]
618pub enum AnimationState {
619    /// Animation hasn't started
620    #[default]
621    Idle,
622    /// Animation is running
623    Running,
624    /// Animation completed
625    Complete,
626}
627
628impl AnimationState {
629    /// Check if animation is idle
630    pub fn is_idle(&self) -> bool {
631        matches!(self, Self::Idle)
632    }
633
634    /// Check if animation is running
635    pub fn is_running(&self) -> bool {
636        matches!(self, Self::Running)
637    }
638
639    /// Check if animation is complete
640    pub fn is_complete(&self) -> bool {
641        matches!(self, Self::Complete)
642    }
643}
644
645/// Calculate smooth pulse scale (sine wave based)
646///
647/// Returns a scale factor that oscillates smoothly
648pub fn pulse_scale(delta: f32, min_scale: f32, max_scale: f32) -> f32 {
649    let oscillation = (delta * std::f32::consts::PI * 2.0).sin();
650    let normalized = (oscillation + 1.0) / 2.0; // Convert -1..1 to 0..1
651    min_scale + (max_scale - min_scale) * normalized
652}
653
654/// Calculate smooth pulse opacity
655///
656/// Returns an opacity value that oscillates smoothly
657pub fn pulse_opacity(delta: f32, min_opacity: f32, max_opacity: f32) -> f32 {
658    let oscillation = (delta * std::f32::consts::PI * 2.0).sin();
659    let normalized = (oscillation + 1.0) / 2.0;
660    min_opacity + (max_opacity - min_opacity) * normalized
661}
662
663/// Calculate shake offset with natural decay
664pub fn shake_offset(delta: f32, max_offset: f32) -> f32 {
665    let frequency = 4.0;
666    let decay = 1.0 - delta;
667    (delta * std::f32::consts::PI * frequency).sin() * max_offset * decay
668}
669
670/// Calculate spring bounce with natural physics
671#[deprecated(note = "unused within the crate and examples; will be removed in 0.10")]
672pub fn spring_bounce(delta: f32, amplitude: f32) -> f32 {
673    let damping = 0.7;
674    let frequency = 1.5;
675    let decay = (-damping * delta * 10.0).exp();
676    let oscillation = (frequency * delta * std::f32::consts::PI * 2.0).sin();
677    amplitude * decay * oscillation
678}
679
680pub fn lerp_f32(from: f32, to: f32, t: f32) -> f32 {
681    from + (to - from) * t.clamp(0.0, 1.0)
682}
683
684pub fn lerp_pixels(from: Pixels, to: Pixels, t: f32) -> Pixels {
685    let t = t.clamp(0.0, 1.0);
686    px(f32::from(from) + (f32::from(to) - f32::from(from)) * t)
687}
688
689pub fn lerp_color(from: Hsla, to: Hsla, t: f32) -> Hsla {
690    let t = t.clamp(0.0, 1.0);
691    // Hue travels the shortest path around the color wheel (h is 0..1).
692    let mut dh = to.h - from.h;
693    if dh > 0.5 {
694        dh -= 1.0;
695    } else if dh < -0.5 {
696        dh += 1.0;
697    }
698    Hsla {
699        h: (from.h + dh * t).rem_euclid(1.0),
700        s: from.s + (to.s - from.s) * t,
701        l: from.l + (to.l - from.l) * t,
702        a: from.a + (to.a - from.a) * t,
703    }
704}
705
706pub fn lerp_shadow(from: &BoxShadow, to: &BoxShadow, t: f32) -> BoxShadow {
707    let t = t.clamp(0.0, 1.0);
708    BoxShadow {
709        color: lerp_color(from.color, to.color, t),
710        offset: point(
711            lerp_pixels(from.offset.x, to.offset.x, t),
712            lerp_pixels(from.offset.y, to.offset.y, t),
713        ),
714        blur_radius: lerp_pixels(from.blur_radius, to.blur_radius, t),
715        spread_radius: lerp_pixels(from.spread_radius, to.spread_radius, t),
716        // `inset` is not interpolatable; keep it if either end uses it.
717        inset: from.inset || to.inset,
718    }
719}
720
721pub fn lerp_shadows(from: &[BoxShadow], to: &[BoxShadow], t: f32) -> SmallVec<[BoxShadow; 2]> {
722    let max_len = from.len().max(to.len());
723    let mut result = SmallVec::new();
724    let empty = BoxShadow {
725        color: hsla(0.0, 0.0, 0.0, 0.0),
726        offset: point(px(0.0), px(0.0)),
727        blur_radius: px(0.0),
728        spread_radius: px(0.0),
729        inset: false,
730    };
731    for i in 0..max_len {
732        let f = from.get(i).unwrap_or(&empty);
733        let t_shadow = to.get(i).unwrap_or(&empty);
734        result.push(lerp_shadow(f, t_shadow, t));
735    }
736    result
737}
738
739#[cfg(test)]
740mod tests {
741    use super::{easings, lerp_color, lerp_shadow};
742    use gpui::{point, px, BoxShadow, Hsla};
743
744    #[test]
745    fn spring_starts_at_zero_and_settles_at_one() {
746        assert_eq!(easings::spring(0.0), 0.0);
747        assert_eq!(easings::spring(1.0), 1.0);
748        assert!(easings::spring(0.5).is_finite());
749    }
750
751    #[test]
752    fn overshoot_easings_are_not_clamped() {
753        assert!(easings::ease_out_back(0.63) > 1.0);
754        assert!(easings::spring(1.0 / 3.0) > 1.0);
755    }
756
757    #[test]
758    fn lerp_color_takes_shortest_hue_path() {
759        let from = Hsla {
760            h: 0.9,
761            s: 1.0,
762            l: 0.5,
763            a: 1.0,
764        };
765        let to = Hsla {
766            h: 0.1,
767            s: 1.0,
768            l: 0.5,
769            a: 1.0,
770        };
771        let mid = lerp_color(from, to, 0.5);
772        // Shortest path crosses 1.0/0.0, not 0.5.
773        assert!(mid.h > 0.9 || mid.h < 0.1, "mid hue was {}", mid.h);
774        let end = lerp_color(from, to, 1.0);
775        assert!((end.h - to.h).abs() < 1e-5);
776    }
777
778    #[test]
779    fn lerp_shadow_preserves_inset() {
780        let base = || BoxShadow {
781            color: Hsla {
782                h: 0.0,
783                s: 0.0,
784                l: 0.0,
785                a: 0.5,
786            },
787            offset: point(px(0.0), px(0.0)),
788            blur_radius: px(4.0),
789            spread_radius: px(0.0),
790            inset: false,
791        };
792        let mut inset_shadow = base();
793        inset_shadow.inset = true;
794
795        assert!(lerp_shadow(&base(), &inset_shadow, 0.5).inset);
796        assert!(lerp_shadow(&inset_shadow, &base(), 0.5).inset);
797        assert!(!lerp_shadow(&base(), &base(), 0.5).inset);
798    }
799}