Skip to main content

sk_css/
animator.rs

1//! The transition animator: diffs the cascade's output, runs the clock and produces a per-frame
2//! overlay `StyleRefinement` applied on top of the computed base. An interrupted transition
3//! retargets from the value it is showing, not from the old computed value.
4
5use std::cell::RefCell;
6use std::collections::{HashMap, HashSet};
7use std::rc::Rc;
8use std::time::{Duration, Instant};
9
10use gpui::{
11    AbsoluteLength, DefiniteLength, EffectCrossFade, EffectSpec, Hsla, Interpolate, Length, Pixels,
12    Rems, StyleRefinement, TransformSpec,
13};
14
15use crate::keyframes::{AnimationSpec, FillMode, Keyframes, Phase, PlayState};
16use crate::transition::{covered, spec_for, Delay, Easing, TransitionProperty, TransitionSpec};
17use crate::ComputedStates;
18
19#[derive(Clone, Copy, Debug, PartialEq)]
20enum Animatable {
21    Number(f32),
22    Color(Hsla),
23    BorderColors([Hsla; 4]),
24    Pixels(Pixels),
25    Rems(Rems),
26    /// The whole spec travels together because only the `params` interpolate; between two specs of
27    /// different effects [`lerp`] cross-fades instead.
28    Effect(EffectSpec),
29    /// A cross-fade between different effects: the first at `1 - t` beneath the second at `t`.
30    EffectFade(EffectSpec, EffectSpec, f32),
31    Transform(TransformSpec),
32    Overflow(gpui::Overflow),
33    ObjectPosition(gpui::ObjectPosition),
34    CornerShape(gpui::CornerShape),
35    TextShadows(TextShadows),
36    /// A sizing length with a `calc-size()` or an intrinsic keyword on one side.
37    Size(SizeForm),
38}
39
40/// `scale * size + fraction% + pixels`, `size` being the basis's intrinsic size: the form both a
41/// `calc-size()` and a plain length take, so the two interpolate.
42#[derive(Clone, Copy, Debug, PartialEq)]
43struct SizeForm {
44    basis: Option<gpui::VnSizeBasis>,
45    scale: f32,
46    fraction: f32,
47    pixels: f32,
48}
49
50impl SizeForm {
51    fn of(length: Length) -> Self {
52        let plain = |fraction: f32, pixels: f32| SizeForm {
53            basis: None,
54            scale: 0.,
55            fraction,
56            pixels,
57        };
58        let definite = |d: DefiniteLength| match d {
59            DefiniteLength::Absolute(a) => {
60                plain(0., a.to_pixels(gpui::px(crate::rem_basis())).into())
61            }
62            DefiniteLength::Fraction(f) => plain(f, 0.),
63            DefiniteLength::Calc { fraction, pixels } => plain(fraction, pixels.into()),
64        };
65        match length {
66            Length::Definite(d) => definite(d),
67            Length::Auto => SizeForm {
68                basis: Some(gpui::VnSizeBasis::Auto),
69                scale: 1.,
70                ..plain(0., 0.)
71            },
72            Length::VnCalcSize(c) => SizeForm {
73                basis: Some(c.basis),
74                scale: c.scale,
75                ..definite(c.offset)
76            },
77        }
78    }
79
80    fn length(self) -> Length {
81        let offset = match (self.fraction, self.pixels) {
82            (f, p) if f == 0. => DefiniteLength::Absolute(gpui::px(p).into()),
83            (f, p) if p == 0. => DefiniteLength::Fraction(f),
84            (fraction, p) => DefiniteLength::Calc {
85                fraction,
86                pixels: gpui::px(p),
87            },
88        };
89        match self.basis {
90            Some(basis) if self.scale != 0. => Length::VnCalcSize(gpui::VnCalcSize {
91                basis,
92                scale: self.scale,
93                offset,
94            }),
95            _ => Length::Definite(offset),
96        }
97    }
98
99    fn lerp(a: Self, b: Self, t: f32) -> Self {
100        SizeForm {
101            basis: a.basis.or(b.basis),
102            scale: f32::interpolate(a.scale, b.scale, t),
103            fraction: f32::interpolate(a.fraction, b.fraction, t),
104            pixels: f32::interpolate(a.pixels, b.pixels, t),
105        }
106    }
107}
108
109fn is_sizing(p: &TransitionProperty) -> bool {
110    use TransitionProperty::*;
111    matches!(
112        p,
113        Width | Height | MinWidth | MinHeight | MaxWidth | MaxHeight
114    )
115}
116
117/// Turns a pair of sizing slots into a pair that interpolates when one side is a `calc-size()`,
118/// or, with `interpolate-size: allow-keywords`, `auto`. `None` leaves the pair as it was.
119fn size_pair(from: Slot, to: Slot, p: &TransitionProperty, keywords: bool) -> Option<(Slot, Slot)> {
120    if !is_sizing(p) {
121        return None;
122    }
123    use TransitionProperty::*;
124    let calc = |s: &Slot| matches!(s, Slot::Value(Animatable::Size(_)));
125    // `auto` meets a `calc-size()` as `calc-size(auto, size)`, which needs no opt-in.
126    let auto = matches!(p, Width | Height | MinWidth | MinHeight)
127        && (keywords || calc(&from) || calc(&to));
128    let lift = |s: Slot| -> Option<SizeForm> {
129        match s {
130            Slot::Value(Animatable::Size(form)) => Some(form),
131            Slot::Value(Animatable::Pixels(px)) => Some(SizeForm::of(Length::Definite(px.into()))),
132            Slot::Value(Animatable::Rems(r)) => Some(SizeForm::of(Length::Definite(r.into()))),
133            Slot::Opaque(Opaque::Fraction(f)) => {
134                Some(SizeForm::of(Length::Definite(DefiniteLength::Fraction(f))))
135            }
136            Slot::Opaque(Opaque::Calc(fraction, pixels)) => {
137                Some(SizeForm::of(Length::Definite(DefiniteLength::Calc {
138                    fraction,
139                    pixels: gpui::px(pixels),
140                })))
141            }
142            Slot::Opaque(Opaque::Auto) if auto => Some(SizeForm::of(Length::Auto)),
143            Slot::Missing if auto => Some(SizeForm::of(Length::Auto)),
144            _ => None,
145        }
146    };
147    let sized = |s: &Slot| match s {
148        Slot::Value(Animatable::Size(_)) => true,
149        Slot::Opaque(Opaque::Auto) | Slot::Missing => auto,
150        _ => false,
151    };
152    if !sized(&from) && !sized(&to) {
153        return None;
154    }
155    let (a, b) = (lift(from)?, lift(to)?);
156    if a.basis.is_some() && b.basis.is_some() && a.basis != b.basis {
157        return None;
158    }
159    Some((
160        Slot::Value(Animatable::Size(a)),
161        Slot::Value(Animatable::Size(b)),
162    ))
163}
164
165/// A longer `text-shadow` list snaps instead of interpolating.
166const MAX_ANIMATED_TEXT_SHADOWS: usize = 4;
167
168/// A `text-shadow` list as a `Copy` value, with the `color` its `currentColor` entries take when
169/// one is interpolated against a concrete colour.
170#[derive(Clone, Copy, Debug)]
171struct TextShadows {
172    shadows: [gpui::TextShadow; MAX_ANIMATED_TEXT_SHADOWS],
173    len: usize,
174    current: Hsla,
175}
176
177impl TextShadows {
178    fn new(list: &[gpui::TextShadow], current: Hsla) -> Option<Self> {
179        if list.len() > MAX_ANIMATED_TEXT_SHADOWS {
180            return None;
181        }
182        let mut shadows = [gpui::TextShadow::default(); MAX_ANIMATED_TEXT_SHADOWS];
183        shadows[..list.len()].copy_from_slice(list);
184        Some(Self {
185            shadows,
186            len: list.len(),
187            current,
188        })
189    }
190
191    fn list(&self) -> &[gpui::TextShadow] {
192        &self.shadows[..self.len]
193    }
194}
195
196/// `current` is not part of the value: a change of `color` alone does not transition `text-shadow`.
197impl PartialEq for TextShadows {
198    fn eq(&self, other: &Self) -> bool {
199        self.list() == other.list()
200    }
201}
202
203#[derive(Clone, Copy, Debug, PartialEq)]
204enum Opaque {
205    Auto,
206    Fraction(f32),
207    Calc(f32, f32),
208    NonSolidFill,
209    /// CSS does not interpolate `none` with a paint either, so the pair is discrete and snaps.
210    UnpaintedSvg,
211    /// A concrete `fill` / `stroke` colour. sk-tree draws it into the serialized `<svg>` document,
212    /// which an overlay refinement cannot reach, so a change of one snaps (and says so).
213    SvgColour(Hsla),
214    /// A `text-shadow` list longer than [`MAX_ANIMATED_TEXT_SHADOWS`].
215    LongTextShadowList,
216}
217
218#[derive(Clone, Copy, Debug, PartialEq)]
219enum Slot {
220    Missing,
221    Value(Animatable),
222    Opaque(Opaque),
223}
224
225fn from_absolute(a: AbsoluteLength) -> Animatable {
226    match a {
227        AbsoluteLength::Pixels(p) => Animatable::Pixels(p),
228        AbsoluteLength::Rems(r) => Animatable::Rems(r),
229    }
230}
231
232fn to_absolute(v: Animatable) -> Option<AbsoluteLength> {
233    match v {
234        Animatable::Pixels(p) => Some(AbsoluteLength::Pixels(p)),
235        Animatable::Rems(r) => Some(AbsoluteLength::Rems(r)),
236        _ => None,
237    }
238}
239
240fn slot_absolute(v: Option<AbsoluteLength>) -> Slot {
241    v.map_or(Slot::Missing, |a| Slot::Value(from_absolute(a)))
242}
243
244fn slot_definite(v: Option<DefiniteLength>) -> Slot {
245    match v {
246        None => Slot::Missing,
247        Some(DefiniteLength::Absolute(a)) => Slot::Value(from_absolute(a)),
248        Some(DefiniteLength::Fraction(f)) => Slot::Opaque(Opaque::Fraction(f)),
249        Some(DefiniteLength::Calc { fraction, pixels }) => {
250            Slot::Opaque(Opaque::Calc(fraction, f32::from(pixels)))
251        }
252    }
253}
254
255fn slot_length(v: Option<Length>) -> Slot {
256    match v {
257        None => Slot::Missing,
258        Some(Length::Auto) => Slot::Opaque(Opaque::Auto),
259        Some(Length::Definite(d)) => slot_definite(Some(d)),
260        Some(c @ Length::VnCalcSize(_)) => Slot::Value(Animatable::Size(SizeForm::of(c))),
261    }
262}
263
264fn slot_shape(v: Option<gpui::CornerShape>) -> Slot {
265    v.map_or(Slot::Missing, |s| Slot::Value(Animatable::CornerShape(s)))
266}
267
268fn slot_color(v: Option<Hsla>) -> Slot {
269    v.map_or(Slot::Missing, |c| Slot::Value(Animatable::Color(c)))
270}
271
272fn slot_text_shadow(r: &StyleRefinement, current: Hsla) -> Slot {
273    match &r.text.text_shadow {
274        None => Slot::Missing,
275        Some(list) => TextShadows::new(list, current)
276            .map_or(Slot::Opaque(Opaque::LongTextShadowList), |shadows| {
277                Slot::Value(Animatable::TextShadows(shadows))
278            }),
279    }
280}
281
282fn slot_of(r: &StyleRefinement, p: &TransitionProperty) -> Slot {
283    use TransitionProperty::*;
284    match p {
285        Opacity => r
286            .opacity
287            .map_or(Slot::Missing, |o| Slot::Value(Animatable::Number(o))),
288        Color => slot_color(r.text.color),
289        BackgroundColor => match &r.background {
290            None => Slot::Missing,
291            Some(gpui::Fill::Color(bg)) => match bg.as_solid() {
292                Some(c) => Slot::Value(Animatable::Color(c)),
293                None => Slot::Opaque(Opaque::NonSolidFill),
294            },
295        },
296        BorderColor => {
297            let side_colors = [
298                &r.vn_border_colors.top,
299                &r.vn_border_colors.right,
300                &r.vn_border_colors.bottom,
301                &r.vn_border_colors.left,
302            ];
303            if r.border_color.is_none() && side_colors.iter().all(|color| color.is_none()) {
304                Slot::Missing
305            } else {
306                let fallback = r.border_color.unwrap_or_default();
307                let colors = side_colors.map(|color| color.flatten().unwrap_or(fallback));
308                if colors.iter().all(|color| *color == colors[0]) {
309                    Slot::Value(Animatable::Color(colors[0]))
310                } else {
311                    Slot::Value(Animatable::BorderColors(colors))
312                }
313            }
314        }
315        TextDecorationColor => slot_color(
316            r.text
317                .underline
318                .as_ref()
319                .and_then(|u| u.color)
320                .or_else(|| r.text.strikethrough.as_ref().and_then(|st| st.color)),
321        ),
322        TextShadow => slot_text_shadow(r, r.text.color.unwrap_or_else(gpui::black)),
323        // A refinement carries no SVG paint; `slot_inherited` answers these from the node's
324        // `Extras`.
325        Fill | Stroke => Slot::Missing,
326        Width => slot_length(r.size.width),
327        Height => slot_length(r.size.height),
328        MinWidth => slot_length(r.min_size.width),
329        MinHeight => slot_length(r.min_size.height),
330        MaxWidth => slot_length(r.max_size.width),
331        MaxHeight => slot_length(r.max_size.height),
332        PaddingTop => slot_definite(r.padding.top),
333        PaddingRight => slot_definite(r.padding.right),
334        PaddingBottom => slot_definite(r.padding.bottom),
335        PaddingLeft => slot_definite(r.padding.left),
336        MarginTop => slot_length(r.margin.top),
337        MarginRight => slot_length(r.margin.right),
338        MarginBottom => slot_length(r.margin.bottom),
339        MarginLeft => slot_length(r.margin.left),
340        BorderTopLeftRadius => slot_absolute(r.corner_radii.top_left),
341        BorderTopRightRadius => slot_absolute(r.corner_radii.top_right),
342        BorderBottomRightRadius => slot_absolute(r.corner_radii.bottom_right),
343        BorderBottomLeftRadius => slot_absolute(r.corner_radii.bottom_left),
344        CornerTopLeftShape => slot_shape(r.vn_corner_shapes.top_left),
345        CornerTopRightShape => slot_shape(r.vn_corner_shapes.top_right),
346        CornerBottomRightShape => slot_shape(r.vn_corner_shapes.bottom_right),
347        CornerBottomLeftShape => slot_shape(r.vn_corner_shapes.bottom_left),
348        BorderTopWidth => slot_absolute(r.border_widths.top),
349        BorderRightWidth => slot_absolute(r.border_widths.right),
350        BorderBottomWidth => slot_absolute(r.border_widths.bottom),
351        BorderLeftWidth => slot_absolute(r.border_widths.left),
352        OverflowX => r
353            .overflow
354            .x
355            .map_or(Slot::Missing, |o| Slot::Value(Animatable::Overflow(o))),
356        OverflowY => r
357            .overflow
358            .y
359            .map_or(Slot::Missing, |o| Slot::Value(Animatable::Overflow(o))),
360        RowGap => slot_definite(r.gap.height),
361        ColumnGap => slot_definite(r.gap.width),
362        FontSize => slot_absolute(r.text.font_size),
363        ObjectPosition => r.vn_object_position.map_or(Slot::Missing, |o| {
364            Slot::Value(Animatable::ObjectPosition(o))
365        }),
366        // `auto` is 0 and `auto <ratio>` negative (the mapper's encoding); neither interpolates.
367        AspectRatio => match r.aspect_ratio {
368            None => Slot::Missing,
369            Some(ratio) if ratio > 0.0 => Slot::Value(Animatable::Number(ratio.ln())),
370            Some(_) => Slot::Opaque(Opaque::Auto),
371        },
372        Shading => r
373            .vn_effect
374            .map_or(Slot::Missing, |e| Slot::Value(Animatable::Effect(e))),
375        Transform => r
376            .vn_transform
377            .map_or(Slot::Missing, |t| Slot::Value(Animatable::Transform(t))),
378        All | Other(_) => Slot::Missing,
379    }
380}
381
382/// `color` is the one animatable property that inherits, so "this rung declares none" is the
383/// parent's colour, not unset; the cascade threads it down (`ComputedStates::color`). Tailwind's
384/// `transition-colors` on a wrapper relies on it.
385fn slot_inherited(
386    r: &StyleRefinement,
387    p: &TransitionProperty,
388    inherited: Option<Hsla>,
389    extras: &crate::Extras,
390) -> Slot {
391    use TransitionProperty::*;
392    match p {
393        Color => match slot_of(r, p) {
394            Slot::Missing => slot_color(inherited),
395            slot => slot,
396        },
397        // `fill` / `stroke` live in `Extras`, and what they animate is the colour the sprite is
398        // tinted with — which is the element's own `color`, because that is the only colour an SVG
399        // has here.
400        Fill => slot_paint(extras.fill, r.text.color.or(inherited)),
401        Stroke => slot_paint(extras.stroke, r.text.color.or(inherited)),
402        TextDecorationColor => match slot_of(r, p) {
403            Slot::Missing if r.text.underline.is_some() || r.text.strikethrough.is_some() => {
404                slot_color(r.text.color.or(inherited))
405            }
406            slot => slot,
407        },
408        TextShadow => slot_text_shadow(r, r.text.color.or(inherited).unwrap_or_else(gpui::black)),
409        _ => slot_of(r, p),
410    }
411}
412
413fn slot_paint(paint: Option<crate::SvgPaint>, color: Option<Hsla>) -> Slot {
414    match paint {
415        None => Slot::Missing,
416        Some(crate::SvgPaint::None) => Slot::Opaque(Opaque::UnpaintedSvg),
417        Some(crate::SvgPaint::Color(c)) => Slot::Opaque(Opaque::SvgColour(c)),
418        Some(_) => slot_color(color),
419    }
420}
421
422fn install(r: &mut StyleRefinement, base: &StyleRefinement, p: &TransitionProperty, v: Animatable) {
423    use TransitionProperty::*;
424    let definite = || to_absolute(v).map(DefiniteLength::Absolute);
425    let length = || match v {
426        Animatable::Size(form) => Some(form.length()),
427        _ => to_absolute(v).map(|a| Length::Definite(DefiniteLength::Absolute(a))),
428    };
429    let color = || match v {
430        Animatable::Color(c) => Some(c),
431        _ => None,
432    };
433    match p {
434        Opacity => {
435            if let Animatable::Number(n) = v {
436                // CSS clamps the used value; an overshooting easing must not paint a negative or >1
437                // alpha.
438                r.opacity = Some(n.clamp(0.0, 1.0));
439            }
440        }
441        Color => r.text.color = color(),
442        BackgroundColor => r.background = color().map(|c| gpui::Fill::Color(c.into())),
443        BorderColor => match v {
444            Animatable::BorderColors(colors) => {
445                r.border_color = Some(colors[0]);
446                r.vn_border_colors.top = Some(Some(colors[0]));
447                r.vn_border_colors.right = Some(Some(colors[1]));
448                r.vn_border_colors.bottom = Some(Some(colors[2]));
449                r.vn_border_colors.left = Some(Some(colors[3]));
450            }
451            Animatable::Color(color) => {
452                r.border_color = Some(color);
453                r.vn_border_colors = gpui::EdgesRefinement {
454                    top: Some(None),
455                    right: Some(None),
456                    bottom: Some(None),
457                    left: Some(None),
458                };
459            }
460            _ => {}
461        },
462        // The decoration is a whole struct in gpui: carry a complete one (thickness, waviness and
463        // offset from the base, colour replaced), since a bare `UnderlineStyle { color }` would
464        // paint a hairline.
465        TextDecorationColor => {
466            if let Some(c) = color() {
467                if let Some(mut u) = r
468                    .text
469                    .underline
470                    .clone()
471                    .or_else(|| base.text.underline.clone())
472                {
473                    u.color = Some(c);
474                    r.text.underline = Some(u);
475                }
476                if let Some(mut st) = r
477                    .text
478                    .strikethrough
479                    .clone()
480                    .or_else(|| base.text.strikethrough.clone())
481                {
482                    st.color = Some(c);
483                    r.text.strikethrough = Some(st);
484                }
485            }
486        }
487        TextShadow => {
488            if let Animatable::TextShadows(shadows) = v {
489                r.text.text_shadow = Some(shadows.list().to_vec());
490            }
491        }
492        Fill | Stroke => r.text.color = color().or(r.text.color),
493        Width => r.size.width = length(),
494        Height => r.size.height = length(),
495        MinWidth => r.min_size.width = length(),
496        MinHeight => r.min_size.height = length(),
497        MaxWidth => r.max_size.width = length(),
498        MaxHeight => r.max_size.height = length(),
499        PaddingTop => r.padding.top = definite(),
500        PaddingRight => r.padding.right = definite(),
501        PaddingBottom => r.padding.bottom = definite(),
502        PaddingLeft => r.padding.left = definite(),
503        MarginTop => r.margin.top = length(),
504        MarginRight => r.margin.right = length(),
505        MarginBottom => r.margin.bottom = length(),
506        MarginLeft => r.margin.left = length(),
507        BorderTopLeftRadius => r.corner_radii.top_left = to_absolute(v),
508        BorderTopRightRadius => r.corner_radii.top_right = to_absolute(v),
509        BorderBottomRightRadius => r.corner_radii.bottom_right = to_absolute(v),
510        BorderBottomLeftRadius => r.corner_radii.bottom_left = to_absolute(v),
511        CornerTopLeftShape
512        | CornerTopRightShape
513        | CornerBottomRightShape
514        | CornerBottomLeftShape => {
515            if let Animatable::CornerShape(shape) = v {
516                let s = &mut r.vn_corner_shapes;
517                *match p {
518                    CornerTopLeftShape => &mut s.top_left,
519                    CornerTopRightShape => &mut s.top_right,
520                    CornerBottomRightShape => &mut s.bottom_right,
521                    _ => &mut s.bottom_left,
522                } = Some(shape);
523            }
524        }
525        BorderTopWidth => r.border_widths.top = to_absolute(v),
526        BorderRightWidth => r.border_widths.right = to_absolute(v),
527        BorderBottomWidth => r.border_widths.bottom = to_absolute(v),
528        BorderLeftWidth => r.border_widths.left = to_absolute(v),
529        OverflowX | OverflowY => {
530            if let Animatable::Overflow(o) = v {
531                if matches!(p, OverflowX) {
532                    r.overflow.x = Some(o);
533                } else {
534                    r.overflow.y = Some(o);
535                }
536            }
537        }
538        RowGap => r.gap.height = definite(),
539        ColumnGap => r.gap.width = definite(),
540        FontSize => r.text.font_size = to_absolute(v),
541        ObjectPosition => {
542            if let Animatable::ObjectPosition(o) = v {
543                r.vn_object_position = Some(o);
544            }
545        }
546        AspectRatio => {
547            if let Animatable::Number(log) = v {
548                r.aspect_ratio = Some(log.exp());
549            }
550        }
551        Shading => match v {
552            Animatable::Effect(spec) => {
553                r.vn_effect = Some(spec);
554                r.vn_effect_fade = None;
555            }
556            Animatable::EffectFade(from, to, progress) => {
557                r.vn_effect = Some(to);
558                r.vn_effect_fade = Some(EffectCrossFade { from, progress });
559            }
560            _ => {}
561        },
562        Transform => {
563            if let Animatable::Transform(spec) = v {
564                r.vn_transform = Some(spec);
565            }
566        }
567        All | Other(_) => {}
568    }
569}
570
571fn clear(r: &mut StyleRefinement, p: &TransitionProperty) {
572    use TransitionProperty::*;
573    match p {
574        Opacity => r.opacity = None,
575        Color => r.text.color = None,
576        TextDecorationColor => {
577            if let Some(u) = r.text.underline.as_mut() {
578                u.color = None;
579            }
580            if let Some(st) = r.text.strikethrough.as_mut() {
581                st.color = None;
582            }
583        }
584        TextShadow => r.text.text_shadow = None,
585        // Take a transitioned property out of the `:hover` rung so gpui cannot snap it.
586        // `fill`/`stroke` paint `color`, which only `transition: color` may animate, so stripping
587        // it here would leave a hover colour painted by nobody.
588        Fill | Stroke => {}
589        BackgroundColor => r.background = None,
590        BorderColor => {
591            r.border_color = None;
592            r.vn_border_colors = Default::default();
593        }
594        Width => r.size.width = None,
595        Height => r.size.height = None,
596        MinWidth => r.min_size.width = None,
597        MinHeight => r.min_size.height = None,
598        MaxWidth => r.max_size.width = None,
599        MaxHeight => r.max_size.height = None,
600        PaddingTop => r.padding.top = None,
601        PaddingRight => r.padding.right = None,
602        PaddingBottom => r.padding.bottom = None,
603        PaddingLeft => r.padding.left = None,
604        MarginTop => r.margin.top = None,
605        MarginRight => r.margin.right = None,
606        MarginBottom => r.margin.bottom = None,
607        MarginLeft => r.margin.left = None,
608        BorderTopLeftRadius => r.corner_radii.top_left = None,
609        BorderTopRightRadius => r.corner_radii.top_right = None,
610        BorderBottomRightRadius => r.corner_radii.bottom_right = None,
611        BorderBottomLeftRadius => r.corner_radii.bottom_left = None,
612        CornerTopLeftShape => r.vn_corner_shapes.top_left = None,
613        CornerTopRightShape => r.vn_corner_shapes.top_right = None,
614        CornerBottomRightShape => r.vn_corner_shapes.bottom_right = None,
615        CornerBottomLeftShape => r.vn_corner_shapes.bottom_left = None,
616        BorderTopWidth => r.border_widths.top = None,
617        BorderRightWidth => r.border_widths.right = None,
618        BorderBottomWidth => r.border_widths.bottom = None,
619        BorderLeftWidth => r.border_widths.left = None,
620        OverflowX => r.overflow.x = None,
621        OverflowY => r.overflow.y = None,
622        RowGap => r.gap.height = None,
623        ColumnGap => r.gap.width = None,
624        FontSize => r.text.font_size = None,
625        ObjectPosition => r.vn_object_position = None,
626        AspectRatio => r.aspect_ratio = None,
627        Shading => {
628            r.vn_effect = None;
629            r.vn_effect_fade = None;
630        }
631        Transform => r.vn_transform = None,
632        All | Other(_) => {}
633    }
634}
635
636fn copy_property(dst: &mut StyleRefinement, src: &StyleRefinement, p: &TransitionProperty) {
637    use TransitionProperty::*;
638    match p {
639        Opacity => dst.opacity = src.opacity,
640        Color => dst.text.color = src.text.color,
641        TextDecorationColor => {
642            dst.text.underline = src.text.underline.clone();
643            dst.text.strikethrough = src.text.strikethrough.clone();
644        }
645        TextShadow => dst.text.text_shadow = src.text.text_shadow.clone(),
646        Fill | Stroke => {}
647        BackgroundColor => dst.background = src.background.clone(),
648        BorderColor => {
649            dst.border_color = src.border_color;
650            dst.vn_border_colors = src.vn_border_colors.clone();
651        }
652        Width => dst.size.width = src.size.width,
653        Height => dst.size.height = src.size.height,
654        MinWidth => dst.min_size.width = src.min_size.width,
655        MinHeight => dst.min_size.height = src.min_size.height,
656        MaxWidth => dst.max_size.width = src.max_size.width,
657        MaxHeight => dst.max_size.height = src.max_size.height,
658        PaddingTop => dst.padding.top = src.padding.top,
659        PaddingRight => dst.padding.right = src.padding.right,
660        PaddingBottom => dst.padding.bottom = src.padding.bottom,
661        PaddingLeft => dst.padding.left = src.padding.left,
662        MarginTop => dst.margin.top = src.margin.top,
663        MarginRight => dst.margin.right = src.margin.right,
664        MarginBottom => dst.margin.bottom = src.margin.bottom,
665        MarginLeft => dst.margin.left = src.margin.left,
666        BorderTopLeftRadius => dst.corner_radii.top_left = src.corner_radii.top_left,
667        BorderTopRightRadius => dst.corner_radii.top_right = src.corner_radii.top_right,
668        BorderBottomRightRadius => dst.corner_radii.bottom_right = src.corner_radii.bottom_right,
669        BorderBottomLeftRadius => dst.corner_radii.bottom_left = src.corner_radii.bottom_left,
670        CornerTopLeftShape => dst.vn_corner_shapes.top_left = src.vn_corner_shapes.top_left,
671        CornerTopRightShape => dst.vn_corner_shapes.top_right = src.vn_corner_shapes.top_right,
672        CornerBottomRightShape => {
673            dst.vn_corner_shapes.bottom_right = src.vn_corner_shapes.bottom_right
674        }
675        CornerBottomLeftShape => {
676            dst.vn_corner_shapes.bottom_left = src.vn_corner_shapes.bottom_left
677        }
678        BorderTopWidth => dst.border_widths.top = src.border_widths.top,
679        BorderRightWidth => dst.border_widths.right = src.border_widths.right,
680        BorderBottomWidth => dst.border_widths.bottom = src.border_widths.bottom,
681        BorderLeftWidth => dst.border_widths.left = src.border_widths.left,
682        OverflowX => dst.overflow.x = src.overflow.x,
683        OverflowY => dst.overflow.y = src.overflow.y,
684        RowGap => dst.gap.height = src.gap.height,
685        ColumnGap => dst.gap.width = src.gap.width,
686        FontSize => dst.text.font_size = src.text.font_size,
687        ObjectPosition => dst.vn_object_position = src.vn_object_position,
688        AspectRatio => dst.aspect_ratio = src.aspect_ratio,
689        Shading => {
690            dst.vn_effect = src.vn_effect;
691            dst.vn_effect_fade = src.vn_effect_fade;
692        }
693        Transform => dst.vn_transform = src.vn_transform,
694        All | Other(_) => {}
695    }
696}
697
698pub fn strip_transitioned(
699    rung: &StyleRefinement,
700    transitions: &[TransitionSpec],
701) -> Option<StyleRefinement> {
702    if transitions.is_empty() {
703        return None;
704    }
705    let properties = covered(transitions);
706    let mut out = rung.clone();
707    let mut touched = false;
708    for p in &properties {
709        if !matches!(slot_of(rung, p), Slot::Missing) {
710            clear(&mut out, p);
711            touched = true;
712        }
713    }
714    touched.then_some(out)
715}
716
717fn initial(p: &TransitionProperty) -> Option<Animatable> {
718    use TransitionProperty::*;
719    match p {
720        Opacity => Some(Animatable::Number(1.0)),
721        BackgroundColor => Some(Animatable::Color(Hsla {
722            h: 0.0,
723            s: 0.0,
724            l: 0.0,
725            a: 0.0,
726        })),
727        PaddingTop
728        | PaddingRight
729        | PaddingBottom
730        | PaddingLeft
731        | MarginTop
732        | MarginRight
733        | MarginBottom
734        | MarginLeft
735        | BorderTopLeftRadius
736        | BorderTopRightRadius
737        | BorderBottomRightRadius
738        | BorderBottomLeftRadius
739        | BorderTopWidth
740        | BorderRightWidth
741        | BorderBottomWidth
742        | BorderLeftWidth
743        | RowGap
744        | ColumnGap => Some(Animatable::Pixels(Pixels::from(0.0))),
745        OverflowX | OverflowY => Some(Animatable::Overflow(gpui::Overflow::Visible)),
746        Transform => Some(Animatable::Transform(TransformSpec::IDENTITY)),
747        ObjectPosition => Some(Animatable::ObjectPosition(gpui::ObjectPosition::default())),
748        CornerTopLeftShape
749        | CornerTopRightShape
750        | CornerBottomRightShape
751        | CornerBottomLeftShape => Some(Animatable::CornerShape(gpui::CornerShape::ROUND)),
752        Shading => Some(Animatable::Effect(EffectSpec::NONE)),
753        TextShadow => TextShadows::new(&[], gpui::black()).map(Animatable::TextShadows),
754        _ => None,
755    }
756}
757
758fn unify(a: Animatable, b: Animatable) -> Option<(Animatable, Animatable)> {
759    use Animatable::*;
760    match (a, b) {
761        (Number(_), Number(_))
762        | (Color(_), Color(_))
763        | (Pixels(_), Pixels(_))
764        | (Rems(_), Rems(_)) => Some((a, b)),
765        (BorderColors(_), BorderColors(_)) => Some((a, b)),
766        (Color(color), BorderColors(colors)) => {
767            Some((BorderColors([color; 4]), BorderColors(colors)))
768        }
769        (BorderColors(colors), Color(color)) => {
770            Some((BorderColors(colors), BorderColors([color; 4])))
771        }
772        (Effect(_), Effect(_)) | (EffectFade(..), Effect(_)) => Some((a, b)),
773        (Transform(_), Transform(_)) => Some((a, b)),
774        (ObjectPosition(_), ObjectPosition(_)) => Some((a, b)),
775        (CornerShape(_), CornerShape(_)) => Some((a, b)),
776        (TextShadows(_), TextShadows(_)) => Some((a, b)),
777        (Size(x), Size(y)) if x.basis.is_none() || y.basis.is_none() || x.basis == y.basis => {
778            Some((a, b))
779        }
780        (Pixels(p), Rems(r)) if r.0 == 0.0 => Some((Pixels(p), Pixels(gpui::Pixels::from(0.0)))),
781        (Pixels(p), Rems(r)) if p.as_f32() == 0.0 => Some((Rems(gpui::Rems(0.0)), Rems(r))),
782        (Rems(r), Pixels(p)) if p.as_f32() == 0.0 => Some((Rems(r), Rems(gpui::Rems(0.0)))),
783        (Rems(r), Pixels(p)) if r.0 == 0.0 => Some((Pixels(gpui::Pixels::from(0.0)), Pixels(p))),
784        _ => None,
785    }
786}
787
788fn lerp(from: Animatable, to: Animatable, t: f32) -> Animatable {
789    use Animatable::*;
790    match (from, to) {
791        (Number(a), Number(b)) => Number(f32::interpolate(a, b, t)),
792        (Color(a), Color(b)) => Color(lerp_color(a, b, t)),
793        (BorderColors(a), BorderColors(b)) => BorderColors(std::array::from_fn(|index| {
794            lerp_color(a[index], b[index], t)
795        })),
796        (Pixels(a), Pixels(b)) => Pixels(gpui::Pixels::interpolate(a, b, t)),
797        (Rems(a), Rems(b)) => Rems(gpui::Rems::interpolate(a, b, t)),
798        (Effect(a), Effect(b)) if a.interpolates_with(&b) => Effect(lerp_effect(a, b, t)),
799        (Effect(a), Effect(b)) => EffectFade(a, b, t),
800        // Retargeted mid-fade: back to (or on to) one of the two keeps fading from where it was;
801        // a third effect fades in over the one showing more.
802        (EffectFade(x, y, s), Effect(c)) if c.interpolates_with(&y) => {
803            EffectFade(x, lerp_effect(y, c, t), s + (1.0 - s) * t)
804        }
805        (EffectFade(x, y, s), Effect(c)) if c.interpolates_with(&x) => {
806            EffectFade(y, lerp_effect(x, c, t), (1.0 - s) + s * t)
807        }
808        (EffectFade(x, y, s), Effect(c)) => {
809            lerp(Effect(if s >= 0.5 { y } else { x }), Effect(c), t)
810        }
811        (Transform(a), Transform(b)) => Transform(a.interpolate(b, t)),
812        (ObjectPosition(a), ObjectPosition(b)) => ObjectPosition(gpui::ObjectPosition {
813            x_fraction: f32::interpolate(a.x_fraction, b.x_fraction, t),
814            x_offset: gpui::Pixels::interpolate(a.x_offset, b.x_offset, t),
815            y_fraction: f32::interpolate(a.y_fraction, b.y_fraction, t),
816            y_offset: gpui::Pixels::interpolate(a.y_offset, b.y_offset, t),
817        }),
818        (CornerShape(a), CornerShape(b)) => CornerShape(a.interpolate(b, t)),
819        (TextShadows(a), TextShadows(b)) => TextShadows(lerp_text_shadows(a, b, t)),
820        (Size(a), Size(b)) => Size(SizeForm::lerp(a, b, t)),
821        _ => to,
822    }
823}
824
825/// CSS pads the shorter list with transparent shadows at zero offset and blur.
826fn lerp_text_shadows(from: TextShadows, to: TextShadows, t: f32) -> TextShadows {
827    let len = from.len.max(to.len);
828    let mut out = to;
829    out.len = len;
830    for index in 0..len {
831        let pick = |shadows: &TextShadows, other: &TextShadows| match shadows.list().get(index) {
832            Some(shadow) => (*shadow, shadow.color.unwrap_or(shadows.current)),
833            None => {
834                let color = other.list()[index]
835                    .color
836                    .unwrap_or(other.current)
837                    .opacity(0.0);
838                (gpui::TextShadow::default(), color)
839            }
840        };
841        let (a, a_color) = pick(&from, &to);
842        let (b, b_color) = pick(&to, &from);
843        out.shadows[index] = gpui::TextShadow {
844            color: match (from.list().get(index), to.list().get(index)) {
845                (Some(x), Some(y)) if x.color.is_none() && y.color.is_none() => None,
846                _ => Some(lerp_color(a_color, b_color, t)),
847            },
848            offset: gpui::point(
849                Pixels::interpolate(a.offset.x, b.offset.x, t),
850                Pixels::interpolate(a.offset.y, b.offset.y, t),
851            ),
852            blur_radius: Pixels::interpolate(a.blur_radius, b.blur_radius, t).max(gpui::px(0.)),
853        };
854    }
855    out
856}
857
858fn lerp_effect(a: EffectSpec, b: EffectSpec, t: f32) -> EffectSpec {
859    let mut spec = b;
860    for (slot, value) in spec.params.iter_mut().enumerate() {
861        *value = f32::interpolate(a.params[slot], b.params[slot], t);
862    }
863    // Keep repainting for as long as EITHER endpoint wants to, or an animated grain would freeze
864    // the moment a transition starts.
865    spec.animated = a.animated || b.animated;
866    spec
867}
868
869/// Mixes premultiplied: mixing raw HSLA swings through the hues in between and makes `transparent`
870/// -> white pass through gray. Channels are clamped because an overshooting easing can leave range.
871fn lerp_color(from: Hsla, to: Hsla, t: f32) -> Hsla {
872    if from == to {
873        return to;
874    }
875    let (a, b) = (gpui::Rgba::from(from), gpui::Rgba::from(to));
876    let alpha = f32::interpolate(a.a, b.a, t).clamp(0.0, 1.0);
877    if alpha <= 0.0 {
878        return Hsla {
879            a: 0.0,
880            ..if t < 0.5 { from } else { to }
881        };
882    }
883    let channel = |x: f32, y: f32| (f32::interpolate(x * a.a, y * b.a, t) / alpha).clamp(0.0, 1.0);
884    Hsla::from(gpui::Rgba {
885        r: channel(a.r, b.r),
886        g: channel(a.g, b.g),
887        b: channel(a.b, b.b),
888        a: alpha,
889    })
890}
891
892#[derive(Clone, Debug)]
893struct Track {
894    property: TransitionProperty,
895    from: Animatable,
896    to: Animatable,
897    start: Instant,
898    delay: Delay,
899    duration: Duration,
900    easing: Easing,
901}
902
903impl Track {
904    fn progress(&self, now: Instant) -> f32 {
905        let elapsed = now.saturating_duration_since(self.start);
906        let Some(running) = self.delay.active(elapsed) else {
907            return 0.0;
908        };
909        if self.duration.is_zero() {
910            return 1.0;
911        }
912        (running.as_secs_f32() / self.duration.as_secs_f32()).clamp(0.0, 1.0)
913    }
914
915    fn value(&self, now: Instant) -> Animatable {
916        lerp(self.from, self.to, self.easing.eval(self.progress(now)))
917    }
918
919    fn end(&self) -> Instant {
920        self.start + self.delay.end_after(self.duration).unwrap_or(self.duration)
921    }
922
923    fn finished(&self, now: Instant) -> bool {
924        now >= self.end()
925    }
926}
927
928#[derive(Default)]
929pub struct Animator {
930    nodes: HashMap<u32, Vec<Track>>,
931    anims: HashMap<u32, Vec<AnimRun>>,
932    registered_samples: RefCell<HashMap<u32, (Instant, Rc<(StyleRefinement, crate::Extras)>)>>,
933    events: Vec<AnimEvent>,
934    /// The held value of a settled state-driven track: the host strips the transitioned properties
935    /// out of the rung it hands gpui, so this is all that keeps the hovered value on screen.
936    states: HashMap<u32, StyleRefinement>,
937    scripts: HashMap<u32, Vec<script::ScriptAnim>>,
938    script_nodes: HashMap<u32, u32>,
939    /// A script animation's clock is in timeline milliseconds, so without it nothing a script
940    /// started can be sampled.
941    timeline_origin: Option<Instant>,
942    warned: HashSet<String>,
943    diagnostics: Vec<String>,
944    reduce_motion: bool,
945    /// Nodes under `interpolate-size: allow-keywords`.
946    keywords: HashSet<u32>,
947}
948
949mod script;
950pub use script::{
951    script_keyframes, ScriptClock, ScriptFrame, ScriptKeyframeNotes, ScriptSample, ScriptTiming,
952};
953
954impl Animator {
955    pub fn new() -> Animator {
956        Animator::default()
957    }
958
959    /// Mirrors `gpui::App::reduce_motion()`. While set, values snap instead of animating (gpui's
960    /// own animations behave the same way); turning it on also cancels whatever is running.
961    pub fn set_reduce_motion(&mut self, reduce_motion: bool) {
962        if reduce_motion && !self.reduce_motion {
963            self.registered_samples.get_mut().clear();
964            self.nodes.clear();
965            let now = Instant::now();
966            for (node, runs) in std::mem::take(&mut self.anims) {
967                for run in runs {
968                    self.cancel_event(node, &run, now);
969                }
970            }
971        }
972        self.reduce_motion = reduce_motion;
973    }
974
975    /// The node's inherited `interpolate-size`: whether `auto` sizes interpolate with lengths.
976    pub fn set_interpolate_keywords(&mut self, node: u32, allow: bool) {
977        if allow {
978            self.keywords.insert(node);
979        } else {
980            self.keywords.remove(&node);
981        }
982    }
983
984    /// `old = None` is the first styling of the node: CSS does not transition initial style, so
985    /// leftover tracks are dropped.
986    pub fn on_computed(
987        &mut self,
988        node: u32,
989        old: Option<&ComputedStates>,
990        new: &ComputedStates,
991        now: Instant,
992    ) {
993        if self.reduce_motion {
994            self.nodes.remove(&node);
995            return;
996        }
997        let Some(old) = old else {
998            self.nodes.remove(&node);
999            return;
1000        };
1001
1002        for spec in new.transitions.iter() {
1003            if let TransitionProperty::Other(name) = &spec.property {
1004                self.warn_once(format!("transition of {name} not animatable yet"));
1005            }
1006        }
1007
1008        if new.transitions.is_empty() {
1009            // The state hold goes with them: with nothing left to strip, the whole rung is gpui's
1010            // again and a leftover hold would double-apply it.
1011            self.nodes.remove(&node);
1012            self.states.remove(&node);
1013            return;
1014        }
1015
1016        let properties = covered(&new.transitions);
1017        let mut tracks = self.nodes.remove(&node).unwrap_or_default();
1018        tracks.retain(|t| properties.contains(&t.property));
1019
1020        for property in &properties {
1021            let Some(spec) = spec_for(&new.transitions, property) else {
1022                continue;
1023            };
1024            let index = tracks.iter().position(|t| t.property == *property);
1025            let running = index.map(|i| tracks[i].value(now));
1026
1027            let from_slot = match running {
1028                Some(v) => Slot::Value(v),
1029                None => slot_inherited(&old.base, property, old.color, &old.extras),
1030            };
1031            let to_slot = slot_inherited(&new.base, property, new.color, &new.extras);
1032
1033            match self.endpoints(node, from_slot, to_slot, property) {
1034                Endpoints::Pair(from, to) => {
1035                    if let Some(i) = index {
1036                        if tracks[i].to == to {
1037                            continue;
1038                        }
1039                    }
1040                    if from == to || spec.is_instant() {
1041                        if let Some(i) = index {
1042                            tracks.remove(i);
1043                        }
1044                        continue;
1045                    }
1046                    let track = Track {
1047                        property: property.clone(),
1048                        from,
1049                        to,
1050                        start: now,
1051                        delay: spec.delay,
1052                        duration: spec.duration,
1053                        easing: spec.easing,
1054                    };
1055                    match index {
1056                        Some(i) => tracks[i] = track,
1057                        None => tracks.push(track),
1058                    }
1059                }
1060                Endpoints::Snap => {
1061                    if let Some(i) = index {
1062                        tracks.remove(i);
1063                    }
1064                }
1065            }
1066        }
1067
1068        if tracks.is_empty() {
1069            self.nodes.remove(&node);
1070        } else {
1071            self.nodes.insert(node, tracks);
1072        }
1073    }
1074
1075    pub fn on_state(
1076        &mut self,
1077        node: u32,
1078        computed: &ComputedStates,
1079        target: Option<&StyleRefinement>,
1080        now: Instant,
1081    ) {
1082        if computed.transitions.is_empty() {
1083            self.states.remove(&node);
1084            self.nodes.remove(&node);
1085            return;
1086        }
1087        let properties = covered(&computed.transitions);
1088        let base = &*computed.base;
1089
1090        // Built first so that the reduce-motion path can take it and skip the animation entirely —
1091        // the state style still has to APPLY, it just applies at once.
1092        let mut hold = StyleRefinement::default();
1093        let mut holds_anything = false;
1094        if let Some(target) = target {
1095            for p in &properties {
1096                let to = slot_of(target, p);
1097                if matches!(to, Slot::Missing) {
1098                    continue;
1099                }
1100                if to == slot_inherited(base, p, computed.color, &computed.extras) {
1101                    continue;
1102                }
1103                match to {
1104                    Slot::Value(v) => {
1105                        install(&mut hold, base, p, v);
1106                        holds_anything = true;
1107                    }
1108                    _ => {
1109                        copy_property(&mut hold, target, p);
1110                        holds_anything = true;
1111                    }
1112                }
1113            }
1114        }
1115
1116        if self.reduce_motion {
1117            self.nodes.remove(&node);
1118            if holds_anything {
1119                self.states.insert(node, hold);
1120            } else {
1121                self.states.remove(&node);
1122            }
1123            return;
1124        }
1125
1126        let previous = self.states.get(&node).cloned();
1127        let mut tracks = self.nodes.remove(&node).unwrap_or_default();
1128        tracks.retain(|t| properties.contains(&t.property));
1129
1130        for property in &properties {
1131            let Some(spec) = spec_for(&computed.transitions, property) else {
1132                continue;
1133            };
1134            let index = tracks.iter().position(|t| t.property == *property);
1135            let running = index.map(|i| tracks[i].value(now));
1136            let from_slot = match running {
1137                Some(v) => Slot::Value(v),
1138                None => match previous.as_ref().map(|p| slot_of(p, property)) {
1139                    Some(Slot::Missing) | None => {
1140                        slot_inherited(base, property, computed.color, &computed.extras)
1141                    }
1142                    Some(s) => s,
1143                },
1144            };
1145            let to_slot = match slot_of(&hold, property) {
1146                Slot::Missing => slot_inherited(base, property, computed.color, &computed.extras),
1147                s => s,
1148            };
1149
1150            match self.endpoints(node, from_slot, to_slot, property) {
1151                Endpoints::Pair(from, to) => {
1152                    if let Some(i) = index {
1153                        if tracks[i].to == to {
1154                            continue;
1155                        }
1156                    }
1157                    if from == to || spec.is_instant() {
1158                        if let Some(i) = index {
1159                            tracks.remove(i);
1160                        }
1161                        continue;
1162                    }
1163                    let track = Track {
1164                        property: property.clone(),
1165                        from,
1166                        to,
1167                        start: now,
1168                        delay: spec.delay,
1169                        duration: spec.duration,
1170                        easing: spec.easing,
1171                    };
1172                    match index {
1173                        Some(i) => tracks[i] = track,
1174                        None => tracks.push(track),
1175                    }
1176                }
1177                Endpoints::Snap => {
1178                    if let Some(i) = index {
1179                        tracks.remove(i);
1180                    }
1181                }
1182            }
1183        }
1184
1185        if tracks.is_empty() {
1186            self.nodes.remove(&node);
1187        } else {
1188            self.nodes.insert(node, tracks);
1189        }
1190        if holds_anything {
1191            self.states.insert(node, hold);
1192        } else {
1193            self.states.remove(&node);
1194        }
1195    }
1196
1197    pub fn holds_state(&self, node: u32) -> bool {
1198        self.states.contains_key(&node)
1199    }
1200
1201    pub fn overlay(
1202        &self,
1203        node: u32,
1204        base: &StyleRefinement,
1205        now: Instant,
1206    ) -> Option<StyleRefinement> {
1207        let mut r = self.animation_overlay(node, base, now);
1208        if let Some(hold) = self.states.get(&node) {
1209            use gpui::Refineable as _;
1210            r.get_or_insert_with(StyleRefinement::default).refine(hold);
1211        }
1212        if let Some(tracks) = self.nodes.get(&node).filter(|t| !t.is_empty()) {
1213            let out = r.get_or_insert_with(StyleRefinement::default);
1214            for track in tracks {
1215                install(out, base, &track.property, track.value(now));
1216            }
1217        }
1218        // Script animations last, so above both: Web Animations sorts script animations after CSS
1219        // animations and transitions in the effect stack.
1220        self.script_overlay(node, base, now, &mut r);
1221        r
1222    }
1223
1224    pub fn any_active(&self, now: Instant) -> bool {
1225        self.nodes
1226            .values()
1227            .any(|tracks| tracks.iter().any(|t| !t.finished(now)))
1228    }
1229
1230    pub fn settles_at(&self) -> Option<Instant> {
1231        self.nodes
1232            .values()
1233            .flat_map(|tracks| tracks.iter())
1234            .map(Track::end)
1235            .max()
1236    }
1237
1238    /// Drops tracks that have reached their target, and says whether any did: the last frame that
1239    /// painted one showed a value short of its end, so one more frame must be drawn.
1240    pub fn finish_settled(&mut self, now: Instant) -> bool {
1241        let mut events = Vec::new();
1242        self.nodes.retain(|&node, tracks| {
1243            tracks.retain(|t| {
1244                if !t.finished(now) {
1245                    return true;
1246                }
1247                events.push(AnimEvent {
1248                    node,
1249                    kind: AnimEventKind::TransitionEnd,
1250                    name: t.property.name().to_string(),
1251                    elapsed: t.duration.as_secs_f32(),
1252                });
1253                false
1254            });
1255            !tracks.is_empty()
1256        });
1257        let settled = !events.is_empty();
1258        self.events.append(&mut events);
1259        settled
1260    }
1261
1262    pub fn gc(&mut self, alive: &dyn Fn(u32) -> bool) {
1263        self.nodes.retain(|&id, _| alive(id));
1264        self.anims.retain(|&id, _| alive(id));
1265        self.registered_samples.get_mut().retain(|&id, _| alive(id));
1266        self.states.retain(|&id, _| alive(id));
1267        self.events.retain(|e| alive(e.node));
1268        // A script animation outlives its target in a browser (its clock and its promises are the
1269        // script's), and that half lives in JS; only the painting half goes with the node.
1270        self.scripts.retain(|&id, _| alive(id));
1271        self.script_nodes.retain(|_, node| alive(*node));
1272        self.keywords.retain(|&id| alive(id));
1273    }
1274
1275    /// Explicitly resets CSS motion state. A stylesheet replacement instead rebinds its keyframes
1276    /// through `on_computed_animations`, preserving clocks.
1277    pub fn clear(&mut self) {
1278        self.registered_samples.get_mut().clear();
1279        self.nodes.clear();
1280        self.states.clear();
1281        self.anims.clear();
1282        self.events.clear();
1283    }
1284
1285    pub fn is_idle(&self) -> bool {
1286        self.nodes.is_empty() && self.anims.is_empty() && self.scripts.is_empty()
1287    }
1288
1289    pub fn take_diagnostics(&mut self) -> Vec<String> {
1290        std::mem::take(&mut self.diagnostics)
1291    }
1292
1293    fn warn_once(&mut self, message: String) {
1294        if self.warned.insert(message.clone()) {
1295            self.diagnostics.push(message);
1296        }
1297    }
1298
1299    fn endpoints(
1300        &mut self,
1301        node: u32,
1302        from: Slot,
1303        to: Slot,
1304        property: &TransitionProperty,
1305    ) -> Endpoints {
1306        if from == to {
1307            return Endpoints::Snap;
1308        }
1309        let keywords = self.keywords.contains(&node);
1310        let (from, to) = size_pair(from, to, property, keywords).unwrap_or((from, to));
1311        if from == to {
1312            return Endpoints::Snap;
1313        }
1314        let (from, to) = match (from, to) {
1315            (Slot::Value(a), Slot::Value(b)) => (a, b),
1316            (Slot::Missing, Slot::Value(b)) => match initial(property) {
1317                Some(a) => (a, b),
1318                None => {
1319                    self.warn_once(format!(
1320                        "transition of {} from an unset value is not animatable yet (v1) — snapping",
1321                        property.name()
1322                    ));
1323                    return Endpoints::Snap;
1324                }
1325            },
1326            (Slot::Value(a), Slot::Missing) => match initial(property) {
1327                Some(b) => (a, b),
1328                None => {
1329                    self.warn_once(format!(
1330                        "transition of {} to an unset value is not animatable yet (v1) — snapping",
1331                        property.name()
1332                    ));
1333                    return Endpoints::Snap;
1334                }
1335            },
1336            (Slot::Opaque(Opaque::LongTextShadowList), _)
1337            | (_, Slot::Opaque(Opaque::LongTextShadowList)) => {
1338                self.warn_once(format!(
1339                    "transition of {} with more than {MAX_ANIMATED_TEXT_SHADOWS} shadows is not \
1340                     animatable — snapping. Animate a shorter list",
1341                    property.name()
1342                ));
1343                return Endpoints::Snap;
1344            }
1345            (Slot::Opaque(Opaque::SvgColour(_)), _) | (_, Slot::Opaque(Opaque::SvgColour(_))) => {
1346                self.warn_once(format!(
1347                    "transition of {} to or from a concrete SVG paint colour is not animatable \
1348                     yet (v1) — snapping",
1349                    property.name()
1350                ));
1351                return Endpoints::Snap;
1352            }
1353            _ => {
1354                self.warn_once(format!(
1355                    "transition of {} between percentage/auto endpoints is not animatable yet \
1356                     (v1) — snapping",
1357                    property.name()
1358                ));
1359                return Endpoints::Snap;
1360            }
1361        };
1362        match unify(from, to) {
1363            Some((from, to)) => Endpoints::Pair(from, to),
1364            None => {
1365                self.warn_once(format!(
1366                    "transition of {} between different length units is not animatable yet (v1) \
1367                     — snapping",
1368                    property.name()
1369                ));
1370                Endpoints::Snap
1371            }
1372        }
1373    }
1374}
1375
1376enum Endpoints {
1377    Pair(Animatable, Animatable),
1378    Snap,
1379}
1380
1381impl Animator {
1382    #[cfg(test)]
1383    fn overlay_test(&self, node: u32, now: Instant) -> Option<StyleRefinement> {
1384        self.overlay(node, &StyleRefinement::default(), now)
1385    }
1386}
1387
1388#[cfg(test)]
1389mod tests {
1390    use super::*;
1391    use gpui::{px, relative, rems, Rgba};
1392    use std::rc::Rc;
1393
1394    fn states(base: StyleRefinement, css: &str) -> ComputedStates {
1395        let transitions = if css.is_empty() {
1396            Vec::new()
1397        } else {
1398            let mut diagnostics = Vec::new();
1399            let (_, t) = crate::parse_inline_with_transitions(css, &mut diagnostics);
1400            assert!(diagnostics.is_empty(), "{diagnostics:?}");
1401            t
1402        };
1403        ComputedStates {
1404            base: Rc::new(base),
1405            transitions: Rc::new(transitions),
1406            ..Default::default()
1407        }
1408    }
1409
1410    fn with_opacity(v: f32) -> StyleRefinement {
1411        let mut r = StyleRefinement::default();
1412        r.opacity = Some(v);
1413        r
1414    }
1415
1416    fn with_width(w: Length) -> StyleRefinement {
1417        let mut r = StyleRefinement::default();
1418        r.size.width = Some(w);
1419        r
1420    }
1421
1422    fn with_radius(radius: AbsoluteLength) -> StyleRefinement {
1423        let mut r = StyleRefinement::default();
1424        r.corner_radii.top_left = Some(radius);
1425        r
1426    }
1427
1428    fn with_opacity_and_radius(o: f32, radius: f32) -> StyleRefinement {
1429        let mut r = with_radius(px(radius).into());
1430        r.opacity = Some(o);
1431        r
1432    }
1433
1434    fn opacity_of(r: &StyleRefinement) -> f32 {
1435        r.opacity.expect("overlay carries opacity")
1436    }
1437
1438    fn t0() -> Instant {
1439        Instant::now()
1440    }
1441
1442    #[test]
1443    fn first_computation_does_not_animate() {
1444        let mut a = Animator::new();
1445        let now = t0();
1446        let new = states(with_opacity(0.0), "transition: opacity 1s linear");
1447        a.on_computed(1, None, &new, now);
1448        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1449        assert!(!a.any_active(now));
1450    }
1451
1452    #[test]
1453    fn diff_start_interpolate_settle() {
1454        let mut a = Animator::new();
1455        let now = t0();
1456        let old = states(with_opacity(0.0), "transition: opacity 1s linear");
1457        let new = states(with_opacity(1.0), "transition: opacity 1s linear");
1458
1459        a.on_computed(1, Some(&old), &new, now);
1460        assert!(a.any_active(now));
1461        assert!(
1462            (opacity_of(&a.overlay(1, &StyleRefinement::default(), now).unwrap()) - 0.0).abs()
1463                < 1e-6
1464        );
1465
1466        let half = now + Duration::from_millis(500);
1467        assert!(
1468            (opacity_of(&a.overlay(1, &StyleRefinement::default(), half).unwrap()) - 0.5).abs()
1469                < 1e-3
1470        );
1471
1472        let end = now + Duration::from_millis(1000);
1473        assert!(
1474            (opacity_of(&a.overlay(1, &StyleRefinement::default(), end).unwrap()) - 1.0).abs()
1475                < 1e-6
1476        );
1477        assert!(!a.any_active(end));
1478
1479        a.finish_settled(end);
1480        assert!(a.overlay(1, &StyleRefinement::default(), end).is_none());
1481        assert!(a.is_idle());
1482    }
1483
1484    #[test]
1485    fn delay_holds_the_start_value() {
1486        let mut a = Animator::new();
1487        let now = t0();
1488        let old = states(with_opacity(0.0), "transition: opacity 1s linear 500ms");
1489        let new = states(with_opacity(1.0), "transition: opacity 1s linear 500ms");
1490        a.on_computed(1, Some(&old), &new, now);
1491
1492        for at in [0, 200, 499] {
1493            let v = opacity_of(&a.overlay_test(1, now + Duration::from_millis(at)).unwrap());
1494            assert!(
1495                v.abs() < 1e-6,
1496                "value moved during the delay at {at}ms: {v}"
1497            );
1498        }
1499        let v = opacity_of(
1500            &a.overlay_test(1, now + Duration::from_millis(1000))
1501                .unwrap(),
1502        );
1503        assert!((v - 0.5).abs() < 1e-3, "{v}");
1504        assert!(a.any_active(now + Duration::from_millis(1000)));
1505        assert!(!a.any_active(now + Duration::from_millis(1500)));
1506    }
1507
1508    #[test]
1509    fn a_negative_delay_starts_part_way_through() {
1510        let mut a = Animator::new();
1511        let now = t0();
1512        let old = states(with_opacity(0.0), "transition: opacity 1s linear -250ms");
1513        let new = states(with_opacity(1.0), "transition: opacity 1s linear -250ms");
1514        a.on_computed(1, Some(&old), &new, now);
1515
1516        let v = opacity_of(&a.overlay_test(1, now).unwrap());
1517        assert!((v - 0.25).abs() < 1e-3, "{v}");
1518        assert!(a.any_active(now + Duration::from_millis(700)));
1519        assert!(!a.any_active(now + Duration::from_millis(750)));
1520
1521        let mut b = Animator::new();
1522        let skipped = "transition: opacity 1s linear -1s";
1523        b.on_computed(
1524            1,
1525            Some(&states(with_opacity(0.0), skipped)),
1526            &states(with_opacity(1.0), skipped),
1527            now,
1528        );
1529        assert!(b.overlay(1, &StyleRefinement::default(), now).is_none());
1530    }
1531
1532    #[test]
1533    fn zero_combined_duration_snaps() {
1534        let mut a = Animator::new();
1535        let now = t0();
1536        let old = states(with_opacity(0.0), "transition: opacity 0s");
1537        let new = states(with_opacity(1.0), "transition: opacity 0s");
1538        a.on_computed(1, Some(&old), &new, now);
1539        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1540    }
1541
1542    #[test]
1543    fn zero_duration_with_delay_jumps_after_the_delay() {
1544        let mut a = Animator::new();
1545        let now = t0();
1546        let old = states(with_opacity(0.0), "transition: opacity 0s 300ms");
1547        let new = states(with_opacity(1.0), "transition: opacity 0s 300ms");
1548        a.on_computed(1, Some(&old), &new, now);
1549        assert!(opacity_of(&a.overlay_test(1, now + Duration::from_millis(100)).unwrap()) < 1e-6);
1550        assert!(
1551            (opacity_of(&a.overlay_test(1, now + Duration::from_millis(400)).unwrap()) - 1.0).abs()
1552                < 1e-6
1553        );
1554    }
1555
1556    #[test]
1557    fn retarget_preserves_visual_continuity() {
1558        let mut a = Animator::new();
1559        let now = t0();
1560        let css = "transition: opacity 1s linear";
1561        let zero = states(with_opacity(0.0), css);
1562        let one = states(with_opacity(1.0), css);
1563
1564        a.on_computed(1, Some(&zero), &one, now);
1565        let mid = now + Duration::from_millis(400);
1566        let at_interrupt = opacity_of(&a.overlay(1, &StyleRefinement::default(), mid).unwrap());
1567        assert!((at_interrupt - 0.4).abs() < 1e-3, "{at_interrupt}");
1568
1569        a.on_computed(1, Some(&one), &zero, mid);
1570        let resumed = opacity_of(&a.overlay(1, &StyleRefinement::default(), mid).unwrap());
1571        assert!(
1572            (resumed - at_interrupt).abs() < 1e-4,
1573            "jumped on retarget: {at_interrupt} -> {resumed}"
1574        );
1575
1576        let later = mid + Duration::from_millis(200);
1577        let v = opacity_of(&a.overlay(1, &StyleRefinement::default(), later).unwrap());
1578        assert!(v < at_interrupt, "{v} should be below {at_interrupt}");
1579        assert!((v - 0.32).abs() < 1e-2, "{v}");
1580        let done = mid + Duration::from_millis(1000);
1581        assert!(opacity_of(&a.overlay(1, &StyleRefinement::default(), done).unwrap()).abs() < 1e-6);
1582    }
1583
1584    #[test]
1585    fn restyle_with_the_same_target_does_not_restart() {
1586        let mut a = Animator::new();
1587        let now = t0();
1588        let css = "transition: opacity 1s linear";
1589        let zero = states(with_opacity(0.0), css);
1590        let one = states(with_opacity(1.0), css);
1591        a.on_computed(1, Some(&zero), &one, now);
1592
1593        let mid = now + Duration::from_millis(500);
1594        a.on_computed(1, Some(&one), &one, mid);
1595        let v = opacity_of(&a.overlay(1, &StyleRefinement::default(), mid).unwrap());
1596        assert!((v - 0.5).abs() < 1e-3, "restarted: {v}");
1597        assert!(!a.any_active(now + Duration::from_millis(1000)));
1598    }
1599
1600    #[test]
1601    fn colors_interpolate_in_srgb() {
1602        let mut a = Animator::new();
1603        let now = t0();
1604        let red: Hsla = Rgba {
1605            r: 1.0,
1606            g: 0.0,
1607            b: 0.0,
1608            a: 1.0,
1609        }
1610        .into();
1611        let blue: Hsla = Rgba {
1612            r: 0.0,
1613            g: 0.0,
1614            b: 1.0,
1615            a: 1.0,
1616        }
1617        .into();
1618        fn mk(c: Hsla) -> StyleRefinement {
1619            let mut r = StyleRefinement::default();
1620            r.background = Some(gpui::Fill::Color(c.into()));
1621            r
1622        }
1623        let old = states(mk(red), "transition: background-color 1s linear");
1624        let new = states(mk(blue), "transition: background-color 1s linear");
1625        a.on_computed(1, Some(&old), &new, now);
1626
1627        let half = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1628        let c = half
1629            .background
1630            .unwrap()
1631            .color()
1632            .unwrap()
1633            .as_solid()
1634            .unwrap();
1635        // Half of each channel: `rgb(128 0 128)`, the purple a browser shows, not the
1636        // full-brightness magenta of the hue arc between them.
1637        let c = Rgba::from(c);
1638        assert!(
1639            (c.r - 0.5).abs() < 1e-3 && c.g < 1e-3 && (c.b - 0.5).abs() < 1e-3,
1640            "{c:?}"
1641        );
1642    }
1643
1644    /// Mixed unpremultiplied, a background fading in from it is gray at half alpha part way; a
1645    /// browser shows the colour it is heading for, at a growing alpha.
1646    #[test]
1647    fn a_colour_fading_in_from_transparent_keeps_its_colour() {
1648        let white: Hsla = Rgba {
1649            r: 1.0,
1650            g: 1.0,
1651            b: 1.0,
1652            a: 1.0,
1653        }
1654        .into();
1655        let clear = Hsla {
1656            h: 0.0,
1657            s: 0.0,
1658            l: 0.0,
1659            a: 0.0,
1660        };
1661        let quarter = Rgba::from(lerp_color(clear, white, 0.25));
1662        assert!((quarter.a - 0.25).abs() < 1e-3, "{quarter:?}");
1663        assert!(
1664            quarter.r > 0.999 && quarter.g > 0.999 && quarter.b > 0.999,
1665            "{quarter:?}"
1666        );
1667        let gray: Hsla = Rgba {
1668            r: 0.5,
1669            g: 0.5,
1670            b: 0.5,
1671            a: 1.0,
1672        }
1673        .into();
1674        let blue: Hsla = Rgba {
1675            r: 0.0,
1676            g: 0.0,
1677            b: 1.0,
1678            a: 1.0,
1679        }
1680        .into();
1681        let half = Rgba::from(lerp_color(gray, blue, 0.5));
1682        assert!(
1683            (half.r - 0.25).abs() < 1e-3 && (half.g - 0.25).abs() < 1e-3,
1684            "{half:?}"
1685        );
1686        assert!((half.b - 0.75).abs() < 1e-3, "{half:?}");
1687        let over = lerp_color(gray, blue, 1.4);
1688        assert!((0.0..=1.0).contains(&over.l) && (0.0..=1.0).contains(&over.a));
1689    }
1690
1691    #[test]
1692    fn pixel_lengths_interpolate() {
1693        let mut a = Animator::new();
1694        let now = t0();
1695        let old = states(with_width(px(100.0).into()), "transition: width 1s linear");
1696        let new = states(with_width(px(200.0).into()), "transition: width 1s linear");
1697        a.on_computed(1, Some(&old), &new, now);
1698        let overlay = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1699        assert_eq!(overlay.size.width, Some(px(125.0).into()));
1700    }
1701
1702    #[test]
1703    fn object_position_interpolates_from_its_centred_initial_value() {
1704        let css = "transition: object-position 1s linear";
1705        let at = |x_fraction: f32, x_offset: f32| {
1706            let mut r = StyleRefinement::default();
1707            r.vn_object_position = Some(gpui::ObjectPosition {
1708                x_fraction,
1709                x_offset: px(x_offset),
1710                ..Default::default()
1711            });
1712            r
1713        };
1714        let mut a = Animator::new();
1715        let now = t0();
1716        a.on_computed(
1717            1,
1718            Some(&states(at(0.0, 0.0), css)),
1719            &states(at(1.0, -20.0), css),
1720            now,
1721        );
1722        let quarter = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
1723        assert_eq!(
1724            quarter.vn_object_position,
1725            Some(at(0.25, -5.0).vn_object_position.unwrap())
1726        );
1727
1728        let mut a = Animator::new();
1729        a.on_computed(
1730            1,
1731            Some(&states(StyleRefinement::default(), css)),
1732            &states(at(1.0, 0.0), css),
1733            now,
1734        );
1735        let half = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1736        assert_eq!(half.vn_object_position.map(|p| p.x_fraction), Some(0.75));
1737    }
1738
1739    #[test]
1740    fn text_shadows_interpolate_pairwise_and_pad_with_transparent() {
1741        fn shadowed(shadows: &[gpui::TextShadow]) -> StyleRefinement {
1742            let mut r = StyleRefinement::default();
1743            r.text.text_shadow = Some(shadows.to_vec());
1744            r
1745        }
1746        let shadow = |x: f32, blur: f32, color: Option<Hsla>| gpui::TextShadow {
1747            color,
1748            offset: gpui::point(px(x), px(x)),
1749            blur_radius: px(blur),
1750        };
1751        let red = Hsla::from(Rgba {
1752            r: 1.0,
1753            g: 0.0,
1754            b: 0.0,
1755            a: 1.0,
1756        });
1757        let mut a = Animator::new();
1758        let now = t0();
1759        let css = "transition: text-shadow 1s linear";
1760        let old = states(shadowed(&[shadow(0.0, 0.0, None)]), css);
1761        let new = states(
1762            shadowed(&[shadow(4.0, 8.0, Some(red)), shadow(2.0, 2.0, Some(red))]),
1763            css,
1764        );
1765        a.on_computed(1, Some(&old), &new, now);
1766        let half = a
1767            .overlay_test(1, now + Duration::from_millis(500))
1768            .and_then(|r| r.text.text_shadow)
1769            .expect("text-shadow transitions");
1770        assert_eq!(half.len(), 2);
1771        assert_eq!(half[0].offset.x, px(2.0));
1772        assert_eq!(half[0].blur_radius, px(4.0));
1773        let first = half[0].color.expect("currentColor meets red");
1774        assert!(
1775            first.h != red.h || first.l != red.l,
1776            "mixed with black: {first:?}"
1777        );
1778        assert_eq!(
1779            half[1].offset.x,
1780            px(1.0),
1781            "the shorter list is padded with zeros"
1782        );
1783        assert_eq!(half[1].blur_radius, px(1.0));
1784        let second = half[1].color.expect("a padded shadow is transparent red");
1785        assert!(
1786            (second.a - 0.5).abs() < 1e-3 && second.h == red.h,
1787            "{second:?}"
1788        );
1789    }
1790
1791    #[test]
1792    fn padding_from_unset_uses_the_css_initial_zero() {
1793        let mut a = Animator::new();
1794        let now = t0();
1795        let mut to = StyleRefinement::default();
1796        to.padding.top = Some(px(20.0).into());
1797        let old = states(StyleRefinement::default(), "transition: padding 1s linear");
1798        let new = states(to, "transition: padding 1s linear");
1799        a.on_computed(1, Some(&old), &new, now);
1800        let overlay = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1801        assert_eq!(overlay.padding.top, Some(px(10.0).into()));
1802        assert!(a.take_diagnostics().is_empty());
1803    }
1804
1805    #[test]
1806    fn percentage_endpoints_snap() {
1807        let mut a = Animator::new();
1808        let now = t0();
1809        let from = with_width(px(100.0).into());
1810        let to = with_width(Length::Definite(relative(0.5)));
1811        let old = states(from, "transition: width 1s linear");
1812        let new = states(to, "transition: width 1s linear");
1813        a.on_computed(1, Some(&old), &new, now);
1814        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1815    }
1816
1817    #[test]
1818    fn auto_endpoint_snaps() {
1819        let mut a = Animator::new();
1820        let now = t0();
1821        let old = states(with_width(Length::Auto), "transition: width 1s linear");
1822        let new = states(with_width(px(200.0).into()), "transition: width 1s linear");
1823        a.on_computed(1, Some(&old), &new, now);
1824        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1825        assert_eq!(a.take_diagnostics().len(), 1);
1826    }
1827
1828    #[test]
1829    fn unchanged_non_animatable_value_is_silent() {
1830        let mut a = Animator::new();
1831        let now = t0();
1832        let auto = states(with_width(Length::Auto), "transition: width 1s linear");
1833        a.on_computed(1, Some(&auto), &auto, now);
1834        assert!(a.take_diagnostics().is_empty());
1835    }
1836
1837    #[test]
1838    fn an_unsupported_property_does_not_animate() {
1839        let mut a = Animator::new();
1840        let now = t0();
1841        let old = states(with_opacity(0.0), "transition: filter 1s");
1842        let new = states(with_opacity(1.0), "transition: filter 1s");
1843        a.on_computed(1, Some(&old), &new, now);
1844        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1845    }
1846
1847    #[test]
1848    fn all_covers_every_animatable_property() {
1849        let mut a = Animator::new();
1850        let now = t0();
1851        let old = states(
1852            with_opacity_and_radius(0.0, 0.0),
1853            "transition: all 1s linear",
1854        );
1855        let new = states(
1856            with_opacity_and_radius(1.0, 8.0),
1857            "transition: all 1s linear",
1858        );
1859        a.on_computed(1, Some(&old), &new, now);
1860        let overlay = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1861        assert!((overlay.opacity.unwrap() - 0.5).abs() < 1e-3);
1862        assert_eq!(overlay.corner_radii.top_left, Some(px(4.0).into()));
1863    }
1864
1865    #[test]
1866    fn removing_the_transition_cancels_running_tracks() {
1867        let mut a = Animator::new();
1868        let now = t0();
1869        let css = "transition: opacity 1s linear";
1870        let old = states(with_opacity(0.0), css);
1871        let new = states(with_opacity(1.0), css);
1872        a.on_computed(1, Some(&old), &new, now);
1873        assert!(a.any_active(now));
1874
1875        let mid = now + Duration::from_millis(300);
1876        let bare = states(with_opacity(1.0), "");
1877        a.on_computed(1, Some(&new), &bare, mid);
1878        assert!(a.overlay(1, &StyleRefinement::default(), mid).is_none());
1879        assert!(!a.any_active(mid));
1880    }
1881
1882    #[test]
1883    fn narrowing_transition_property_cancels_the_dropped_one() {
1884        let mut a = Animator::new();
1885        let now = t0();
1886        let old = states(
1887            with_opacity_and_radius(0.0, 0.0),
1888            "transition: all 1s linear",
1889        );
1890        let new = states(
1891            with_opacity_and_radius(1.0, 8.0),
1892            "transition: all 1s linear",
1893        );
1894        a.on_computed(1, Some(&old), &new, now);
1895        let mid = now + Duration::from_millis(200);
1896        assert!(a
1897            .overlay(1, &StyleRefinement::default(), mid)
1898            .unwrap()
1899            .corner_radii
1900            .top_left
1901            .is_some());
1902
1903        let narrowed = states(
1904            with_opacity_and_radius(1.0, 8.0),
1905            "transition: opacity 1s linear",
1906        );
1907        a.on_computed(1, Some(&new), &narrowed, mid);
1908        let overlay = a.overlay(1, &StyleRefinement::default(), mid).unwrap();
1909        assert!(overlay.corner_radii.top_left.is_none());
1910        assert!(overlay.opacity.is_some());
1911    }
1912
1913    #[test]
1914    fn gc_and_clear_drop_node_state() {
1915        let mut a = Animator::new();
1916        let now = t0();
1917        let css = "transition: opacity 1s linear";
1918        let old = states(with_opacity(0.0), css);
1919        let new = states(with_opacity(1.0), css);
1920        a.on_computed(1, Some(&old), &new, now);
1921        a.on_computed(2, Some(&old), &new, now);
1922        assert!(a.overlay(2, &StyleRefinement::default(), now).is_some());
1923
1924        a.gc(&|id| id == 1);
1925        assert!(a.overlay(2, &StyleRefinement::default(), now).is_none());
1926        assert!(a.overlay(1, &StyleRefinement::default(), now).is_some());
1927
1928        a.clear();
1929        assert!(a.is_idle());
1930    }
1931
1932    #[test]
1933    fn reduce_motion_snaps_and_cancels() {
1934        let mut a = Animator::new();
1935        let now = t0();
1936        let css = "transition: opacity 1s linear";
1937        let old = states(with_opacity(0.0), css);
1938        let new = states(with_opacity(1.0), css);
1939        a.on_computed(1, Some(&old), &new, now);
1940        assert!(a.any_active(now));
1941
1942        a.set_reduce_motion(true);
1943        assert!(a.is_idle());
1944        a.on_computed(1, Some(&old), &new, now);
1945        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1946
1947        a.set_reduce_motion(false);
1948        a.on_computed(1, Some(&old), &new, now);
1949        assert!(a.overlay(1, &StyleRefinement::default(), now).is_some());
1950    }
1951
1952    #[test]
1953    fn settles_at_reports_the_last_end() {
1954        let mut a = Animator::new();
1955        let now = t0();
1956        let old = states(with_opacity(0.0), "transition: opacity 1s linear");
1957        let new = states(with_opacity(1.0), "transition: opacity 1s linear");
1958        a.on_computed(1, Some(&old), &new, now);
1959        let settle = a.settles_at().unwrap();
1960        assert!(settle >= now + Duration::from_millis(999));
1961        assert!(settle <= now + Duration::from_millis(1001));
1962    }
1963
1964    #[test]
1965    fn zero_px_and_zero_rem_unify() {
1966        let mut a = Animator::new();
1967        let now = t0();
1968        let old = states(
1969            with_radius(AbsoluteLength::Rems(rems(0.0))),
1970            "transition: border-radius 1s linear",
1971        );
1972        let new = states(
1973            with_radius(px(10.0).into()),
1974            "transition: border-radius 1s linear",
1975        );
1976        a.on_computed(1, Some(&old), &new, now);
1977        let overlay = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
1978        assert_eq!(overlay.corner_radii.top_left, Some(px(5.0).into()));
1979        assert!(a.take_diagnostics().is_empty());
1980    }
1981
1982    #[test]
1983    fn mixed_px_rem_endpoints_snap() {
1984        let mut a = Animator::new();
1985        let now = t0();
1986        let old = states(
1987            with_radius(AbsoluteLength::Rems(rems(1.0))),
1988            "transition: border-radius 1s linear",
1989        );
1990        let new = states(
1991            with_radius(px(10.0).into()),
1992            "transition: border-radius 1s linear",
1993        );
1994        a.on_computed(1, Some(&old), &new, now);
1995        assert!(a.overlay(1, &StyleRefinement::default(), now).is_none());
1996        assert_eq!(a.take_diagnostics().len(), 1);
1997    }
1998
1999    #[test]
2000    fn per_property_specs_use_their_own_timing() {
2001        let mut a = Animator::new();
2002        let now = t0();
2003        let css = "transition: opacity 1s linear, border-top-left-radius 2s linear";
2004        let old = states(with_opacity_and_radius(0.0, 0.0), css);
2005        let new = states(with_opacity_and_radius(1.0, 100.0), css);
2006        a.on_computed(1, Some(&old), &new, now);
2007
2008        let at = now + Duration::from_millis(1000);
2009        let overlay = a.overlay(1, &StyleRefinement::default(), at).unwrap();
2010        assert!((overlay.opacity.unwrap() - 1.0).abs() < 1e-6);
2011        assert_eq!(overlay.corner_radii.top_left, Some(px(50.0).into()));
2012        assert!(a.any_active(at));
2013        assert!(!a.any_active(now + Duration::from_millis(2000)));
2014    }
2015
2016    #[test]
2017    fn easing_shapes_the_curve() {
2018        let mut a = Animator::new();
2019        let now = t0();
2020        let old = states(with_opacity(0.0), "transition: opacity 1s ease-in");
2021        let new = states(with_opacity(1.0), "transition: opacity 1s ease-in");
2022        a.on_computed(1, Some(&old), &new, now);
2023        let v = opacity_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
2024        assert!((v - 0.3154).abs() < 2e-3, "{v}");
2025    }
2026
2027    #[test]
2028    fn overshooting_easing_is_clamped_for_opacity() {
2029        let mut a = Animator::new();
2030        let now = t0();
2031        let css = "transition: opacity 1s cubic-bezier(0.34, 1.8, 0.64, 1)";
2032        let old = states(with_opacity(0.0), css);
2033        let new = states(with_opacity(1.0), css);
2034        a.on_computed(1, Some(&old), &new, now);
2035        for step in 0..=20 {
2036            let v = opacity_of(
2037                &a.overlay_test(1, now + Duration::from_millis(step * 50))
2038                    .unwrap(),
2039            );
2040            assert!((0.0..=1.0).contains(&v), "opacity left 0..1: {v}");
2041        }
2042    }
2043
2044    fn with_shading(value: &str) -> StyleRefinement {
2045        let mut diagnostics = Vec::new();
2046        let r = crate::parse_inline(&format!("--shading: {value}"), &mut diagnostics);
2047        assert!(diagnostics.is_empty(), "{diagnostics:?}");
2048        assert!(r.vn_effect.is_some(), "--shading: {value} did not map");
2049        r
2050    }
2051
2052    fn shading_of(r: &StyleRefinement) -> EffectSpec {
2053        r.vn_effect.expect("overlay carries --shading")
2054    }
2055
2056    #[test]
2057    fn effect_params_interpolate() {
2058        let mut a = Animator::new();
2059        let now = t0();
2060        let css = "transition: --shading 1s linear";
2061        let old = states(with_shading("frost(0.2, 8px)"), css);
2062        let new = states(with_shading("frost(0.8, 20px)"), css);
2063        a.on_computed(1, Some(&old), &new, now);
2064
2065        let half = shading_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
2066        assert_eq!(half.id, gpui::effect_id::FROST);
2067        assert!((half.params[0] - 0.5).abs() < 1e-3, "{}", half.params[0]);
2068        assert!((half.params[1] - 14.0).abs() < 1e-3, "{}", half.params[1]);
2069        assert_eq!(half.backdrop_blur_radius(), half.params[1]);
2070        assert!(a.take_diagnostics().is_empty());
2071
2072        let end = shading_of(
2073            &a.overlay_test(1, now + Duration::from_millis(1000))
2074                .unwrap(),
2075        );
2076        assert_eq!(end.params[0], 0.8);
2077        assert_eq!(end.params[1], 20.0);
2078    }
2079
2080    #[test]
2081    fn effect_color_params_interpolate_componentwise() {
2082        let mut a = Animator::new();
2083        let now = t0();
2084        let css = "transition: --shading 1s linear";
2085        let old = states(with_shading("glow(#000000, 10px, 0)"), css);
2086        let new = states(with_shading("glow(#ffffff, 30px, 1)"), css);
2087        a.on_computed(1, Some(&old), &new, now);
2088        let half = shading_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
2089        assert!((half.params[0] - 20.0).abs() < 1e-3);
2090        assert!((half.params[1] - 0.5).abs() < 1e-3);
2091        for channel in 4..7 {
2092            assert!((half.params[channel] - 0.5).abs() < 1e-3, "slot {channel}");
2093        }
2094        assert!((half.bleed() - 20.0).abs() < 1e-3);
2095    }
2096
2097    #[test]
2098    fn the_same_effect_with_another_image_cross_fades() {
2099        crate::mapper::effect::tests::with_user_effects();
2100        let mut a = Animator::new();
2101        let now = t0();
2102        let css = "transition: --shading 1s linear";
2103        let old = states(with_shading("grade(url(a.png), 0)"), css);
2104        let new = states(with_shading("grade(url(b.png), 1)"), css);
2105        a.on_computed(1, Some(&old), &new, now);
2106        let half = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
2107        let fade = half.vn_effect_fade.expect("a different image cross-fades");
2108        let source = |spec: &EffectSpec| spec.textures[0].unwrap().source;
2109        assert_eq!(source(&fade.from), sk_effects::texture_source("a.png"));
2110        assert_eq!(
2111            source(&shading_of(&half)),
2112            sk_effects::texture_source("b.png")
2113        );
2114        assert_eq!(
2115            fade.from.params[2], 0.0,
2116            "each side keeps its own parameters"
2117        );
2118
2119        let same = states(with_shading("grade(url(b.png), 0.5)"), css);
2120        a.on_computed(2, Some(&new), &same, now);
2121        let r = a.overlay_test(2, now + Duration::from_millis(500)).unwrap();
2122        assert!(r.vn_effect_fade.is_none(), "the same image interpolates");
2123        assert!((shading_of(&r).params[2] - 0.75).abs() < 1e-3);
2124    }
2125
2126    #[test]
2127    fn different_effects_cross_fade() {
2128        let mut a = Animator::new();
2129        let now = t0();
2130        let css = "transition: --shading 1s linear";
2131        let old = states(with_shading("frost(0.5)"), css);
2132        let new = states(with_shading("glow(10px, 0.5)"), css);
2133        a.on_computed(1, Some(&old), &new, now);
2134        let half = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
2135        let fade = half.vn_effect_fade.expect("a cross-fade");
2136        assert_eq!(fade.from.id, gpui::effect_id::FROST);
2137        assert_eq!(shading_of(&half).id, gpui::effect_id::GLOW);
2138        assert!((fade.progress - 0.25).abs() < 1e-3);
2139        assert!(a.take_diagnostics().is_empty());
2140
2141        // Back to frost halfway in: frost grows from the share it had, glow is what fades.
2142        let back = states(with_shading("frost(0.5)"), css);
2143        a.on_computed(1, Some(&new), &back, now + Duration::from_millis(250));
2144        let r = a.overlay_test(1, now + Duration::from_millis(750)).unwrap();
2145        let fade = r.vn_effect_fade.expect("still a cross-fade");
2146        assert_eq!(fade.from.id, gpui::effect_id::GLOW);
2147        assert_eq!(shading_of(&r).id, gpui::effect_id::FROST);
2148        assert!((fade.progress - 0.875).abs() < 1e-3);
2149    }
2150
2151    #[test]
2152    fn all_does_not_cover_shading_but_naming_it_does() {
2153        let mut a = Animator::new();
2154        let now = t0();
2155        let all = "transition: all 1s linear";
2156        let old = states(with_shading("frost(0.2)"), all);
2157        let new = states(with_shading("frost(0.8)"), all);
2158        a.on_computed(1, Some(&old), &new, now);
2159        assert!(
2160            a.overlay(1, &StyleRefinement::default(), now).is_none(),
2161            "`all` must not cover --shading"
2162        );
2163        assert!(a.take_diagnostics().is_empty());
2164
2165        let named = "transition: all 1s linear, --shading 1s linear";
2166        let old = states(with_shading("frost(0.2)"), named);
2167        let new = states(with_shading("frost(0.8)"), named);
2168        a.on_computed(2, Some(&old), &new, now);
2169        assert!(a.overlay(2, &StyleRefinement::default(), now).is_some());
2170    }
2171
2172    #[test]
2173    fn transitioning_to_none_fades_out() {
2174        let mut a = Animator::new();
2175        let now = t0();
2176        let css = "transition: --shading 1s linear";
2177        let old = states(with_shading("frost(0.5)"), css);
2178        let new = states(with_shading("none"), css);
2179        a.on_computed(1, Some(&old), &new, now);
2180        let r = a.overlay_test(1, now + Duration::from_millis(500)).unwrap();
2181        assert!(!shading_of(&r).is_some());
2182        assert_eq!(
2183            r.vn_effect_fade.map(|f| f.from.id),
2184            Some(gpui::effect_id::FROST)
2185        );
2186    }
2187
2188    #[test]
2189    fn an_effect_fades_in_from_and_out_to_an_unset_value() {
2190        let mut a = Animator::new();
2191        let now = t0();
2192        let css = "transition: --shading 1s linear";
2193        let unset = states(StyleRefinement::default(), css);
2194        let glow = states(with_shading("glow(10px, 0.5)"), css);
2195
2196        a.on_computed(1, Some(&unset), &glow, now);
2197        let r = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
2198        assert_eq!(shading_of(&r).id, gpui::effect_id::GLOW);
2199        let fade = r.vn_effect_fade.expect("appearing fades in");
2200        assert!(!fade.from.is_some());
2201        assert!((fade.progress - 0.25).abs() < 1e-3);
2202
2203        let mut a = Animator::new();
2204        a.on_computed(1, Some(&glow), &unset, now);
2205        let r = a.overlay_test(1, now + Duration::from_millis(250)).unwrap();
2206        assert!(!shading_of(&r).is_some());
2207        let fade = r.vn_effect_fade.expect("disappearing fades out");
2208        assert_eq!(fade.from.id, gpui::effect_id::GLOW);
2209        assert!((fade.progress - 0.25).abs() < 1e-3);
2210    }
2211
2212    #[test]
2213    fn an_animated_endpoint_keeps_the_whole_transition_animated() {
2214        let mut a = Animator::new();
2215        let now = t0();
2216        let css = "transition: --shading 1s linear";
2217        let old = states(with_shading("noise(0.1, 2px, 0)"), css);
2218        let new = states(with_shading("noise(0.6, 2px, 24)"), css);
2219        a.on_computed(1, Some(&old), &new, now);
2220        let half = shading_of(&a.overlay_test(1, now + Duration::from_millis(500)).unwrap());
2221        assert!(half.animated, "grain must not freeze mid-transition");
2222        assert!((half.params[0] - 0.35).abs() < 1e-3);
2223        assert!((half.params[2] - 12.0).abs() < 1e-3);
2224    }
2225
2226    fn rgb(r: f32, g: f32, b: f32) -> Hsla {
2227        Rgba { r, g, b, a: 1.0 }.into()
2228    }
2229
2230    fn svg_states(c: Hsla, paint: Option<crate::SvgPaint>, css: &str) -> ComputedStates {
2231        let mut base = StyleRefinement::default();
2232        base.text.color = Some(c);
2233        let mut s = states(base, css);
2234        s.extras = crate::Extras {
2235            fill: paint,
2236            stroke: paint,
2237            ..Default::default()
2238        };
2239        s.color = Some(c);
2240        s
2241    }
2242
2243    #[test]
2244    fn a_fill_track_follows_the_colour_the_sprite_is_tinted_with() {
2245        for css in ["transition: fill 1s linear", "transition: stroke 1s linear"] {
2246            let mut a = Animator::new();
2247            let now = t0();
2248            let (red, blue) = (rgb(1.0, 0.0, 0.0), rgb(0.0, 0.0, 1.0));
2249            let old = svg_states(red, Some(crate::SvgPaint::Current), css);
2250            let new = svg_states(blue, Some(crate::SvgPaint::Current), css);
2251
2252            a.on_computed(1, Some(&old), &new, now);
2253            assert!(a.any_active(now), "{css} must start a track");
2254
2255            let at = |ms: u64| {
2256                a.overlay_test(1, now + Duration::from_millis(ms))
2257                    .and_then(|r| r.text.color)
2258                    .unwrap_or_else(|| panic!("{css}: no tint at {ms}ms"))
2259            };
2260            let same = |a: Hsla, b: Hsla| {
2261                (a.h - b.h).abs() < 1e-4
2262                    && (a.s - b.s).abs() < 1e-4
2263                    && (a.l - b.l).abs() < 1e-4
2264                    && (a.a - b.a).abs() < 1e-4
2265            };
2266            assert!(same(at(0), red), "{css} starts where it was: {:?}", at(0));
2267            assert!(
2268                same(at(1000), blue),
2269                "{css} ends where it is going: {:?}",
2270                at(1000)
2271            );
2272            let half = at(500);
2273            assert!(
2274                !same(half, red) && !same(half, blue),
2275                "{css} interpolates: {half:?}"
2276            );
2277        }
2278    }
2279
2280    #[test]
2281    fn an_svg_paint_of_none_snaps_instead_of_interpolating() {
2282        let mut a = Animator::new();
2283        let now = t0();
2284        let css = "transition: fill 1s linear";
2285        let old = svg_states(rgb(1.0, 0.0, 0.0), Some(crate::SvgPaint::None), css);
2286        let new = svg_states(rgb(0.0, 0.0, 1.0), Some(crate::SvgPaint::Current), css);
2287
2288        a.on_computed(1, Some(&old), &new, now);
2289        assert!(
2290            !a.any_active(now),
2291            "an unpainted endpoint has nothing to interpolate"
2292        );
2293        assert!(a.overlay_test(1, now).is_none());
2294
2295        let bare = svg_states(rgb(0.0, 0.0, 1.0), None, css);
2296        a.on_computed(2, Some(&bare), &bare, now);
2297        assert!(a.overlay_test(2, now).is_none());
2298    }
2299
2300    #[test]
2301    fn text_decoration_color_animates_without_refining_the_line_away() {
2302        fn decorated(c: Hsla) -> StyleRefinement {
2303            let mut r = StyleRefinement::default();
2304            r.text.underline = Some(gpui::UnderlineStyle {
2305                thickness: px(3.0),
2306                color: Some(c),
2307                wavy: true,
2308                offset: px(2.0),
2309            });
2310            r
2311        }
2312        let mut a = Animator::new();
2313        let now = t0();
2314        let css = "transition: text-decoration-color 1s linear";
2315        let (red, blue) = (rgb(1.0, 0.0, 0.0), rgb(0.0, 0.0, 1.0));
2316        let old = states(decorated(red), css);
2317        let new = states(decorated(blue), css);
2318
2319        a.on_computed(1, Some(&old), &new, now);
2320        assert!(a.any_active(now));
2321        let base = decorated(red);
2322        let half = a
2323            .overlay(1, &base, now + Duration::from_millis(500))
2324            .unwrap();
2325        let u = half
2326            .text
2327            .underline
2328            .clone()
2329            .expect("the overlay carries a decoration");
2330        assert_eq!(
2331            u.thickness,
2332            px(3.0),
2333            "the base's thickness survives the overlay"
2334        );
2335        assert!(u.wavy, "…and so does its waviness");
2336        assert_eq!(u.offset, px(2.0), "…and its offset");
2337        let c = u.color.expect("with a colour of its own");
2338        assert!(c != red && c != blue, "interpolated, not snapped: {c:?}");
2339
2340        let end = a
2341            .overlay(1, &base, now + Duration::from_millis(1000))
2342            .unwrap();
2343        let ended = end
2344            .text
2345            .underline
2346            .and_then(|u| u.color)
2347            .expect("a colour at the end");
2348        assert!(
2349            (ended.h - blue.h).abs() < 1e-4 && (ended.l - blue.l).abs() < 1e-4,
2350            "{ended:?}"
2351        );
2352    }
2353}
2354
2355/// It holds its own `Rc<Keyframes>` rather than a name, because `overlay()` is called from the
2356/// render walk — which has a node id and a clock and no engine.
2357struct AnimRun {
2358    spec: AnimationSpec,
2359    frames: Rc<Keyframes>,
2360    custom_context: Option<Rc<crate::CustomAnimationContext>>,
2361    start: Instant,
2362    pending: bool,
2363    started: bool,
2364    ended: bool,
2365    paused_for: Duration,
2366    paused_at: Option<Instant>,
2367}
2368
2369impl AnimRun {
2370    fn elapsed(&self, now: Instant) -> Duration {
2371        let raw = now.saturating_duration_since(self.start);
2372        let paused = self.paused_for
2373            + self
2374                .paused_at
2375                .map(|at| now.saturating_duration_since(at))
2376                .unwrap_or_default();
2377        raw.saturating_sub(paused)
2378    }
2379
2380    fn phase(&self, now: Instant) -> Phase {
2381        self.spec.phase(self.elapsed(now))
2382    }
2383
2384    fn paint_progress(&self, now: Instant) -> Option<f32> {
2385        match self.phase(now) {
2386            Phase::Running { progress, .. } => Some(progress),
2387            Phase::Delayed if matches!(self.spec.fill, FillMode::Backwards | FillMode::Both) => {
2388                Some(self.spec.phase(self.spec.delay.wait()).progress_or(0.0))
2389            }
2390            Phase::Finished { progress }
2391                if matches!(self.spec.fill, FillMode::Forwards | FillMode::Both) =>
2392            {
2393                Some(progress)
2394            }
2395            _ => None,
2396        }
2397    }
2398
2399    fn elapsed_seconds(&self, now: Instant) -> f32 {
2400        self.spec.active_time(self.elapsed(now)).as_secs_f32()
2401    }
2402}
2403
2404#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2405pub enum AnimEventKind {
2406    TransitionEnd,
2407    AnimationStart,
2408    AnimationEnd,
2409    AnimationCancel,
2410}
2411
2412#[derive(Clone, Debug)]
2413pub struct AnimEvent {
2414    pub node: u32,
2415    pub kind: AnimEventKind,
2416    pub name: String,
2417    /// `elapsedTime` in SECONDS, excluding the delay — the DOM's definition.
2418    pub elapsed: f32,
2419}
2420
2421impl Animator {
2422    pub fn on_computed_animations(
2423        &mut self,
2424        node: u32,
2425        new: &ComputedStates,
2426        now: Instant,
2427        resolve: &dyn Fn(&str) -> Option<Rc<Keyframes>>,
2428    ) {
2429        self.registered_samples.get_mut().remove(&node);
2430        let wanted: Vec<AnimationSpec> = if self.reduce_motion {
2431            Vec::new()
2432        } else {
2433            new.animations
2434                .iter()
2435                .filter(|s| !s.is_inert())
2436                .cloned()
2437                .collect()
2438        };
2439
2440        if wanted.is_empty() {
2441            if let Some(runs) = self.anims.remove(&node) {
2442                for run in runs {
2443                    self.cancel_event(node, &run, now);
2444                }
2445            }
2446            return;
2447        }
2448
2449        let mut previous = self.anims.remove(&node).unwrap_or_default();
2450        let mut runs: Vec<AnimRun> = Vec::with_capacity(wanted.len());
2451        for spec in wanted {
2452            // CSS restarts an animation when its NAME changes at that position in the list, and
2453            // only then: changing the duration or the easing retargets a RUNNING animation rather
2454            // than replaying it.
2455            let existing = previous.iter().position(|r| r.spec.name == spec.name);
2456            let Some(frames) = resolve(&spec.name) else {
2457                self.warn_once(format!(
2458                    "`animation-name: {}` names no @keyframes block in the stylesheet — \
2459                     nothing animates (a browser behaves the same way)",
2460                    spec.name
2461                ));
2462                continue;
2463            };
2464            match existing {
2465                Some(i) => {
2466                    let mut run = previous.remove(i);
2467                    match (run.paused_at, spec.play_state) {
2468                        (None, PlayState::Paused) => run.paused_at = Some(now),
2469                        (Some(at), PlayState::Running) => {
2470                            run.paused_for += now.saturating_duration_since(at);
2471                            run.paused_at = None;
2472                        }
2473                        _ => {}
2474                    }
2475                    run.spec = spec;
2476                    run.frames = frames;
2477                    run.custom_context = new.custom_animation.clone();
2478                    runs.push(run);
2479                }
2480                None => {
2481                    runs.push(AnimRun {
2482                        paused_at: (spec.play_state == PlayState::Paused).then_some(now),
2483                        spec,
2484                        frames,
2485                        custom_context: new.custom_animation.clone(),
2486                        start: now,
2487                        pending: true,
2488                        started: false,
2489                        ended: false,
2490                        paused_for: Duration::ZERO,
2491                    });
2492                }
2493            }
2494        }
2495        let leftovers: Vec<AnimRun> = previous;
2496        for run in leftovers {
2497            self.cancel_event(node, &run, now);
2498        }
2499        if runs.is_empty() {
2500            self.anims.remove(&node);
2501        } else {
2502            self.anims.insert(node, runs);
2503        }
2504    }
2505
2506    pub fn cancel_animations(&mut self, node: u32, now: Instant) {
2507        self.registered_samples.get_mut().remove(&node);
2508        if let Some(runs) = self.anims.remove(&node) {
2509            for run in runs {
2510                self.cancel_event(node, &run, now);
2511            }
2512        }
2513    }
2514
2515    pub fn has_animations(&self, node: u32) -> bool {
2516        self.anims.contains_key(&node)
2517    }
2518
2519    /// No CSS animation of `node` is still to finish; a paused one is not finished.
2520    pub fn animations_finished(&self, node: u32, now: Instant) -> bool {
2521        self.anims.get(&node).is_none_or(|runs| {
2522            runs.iter().all(|run| {
2523                run.paused_at.is_none() && matches!(run.phase(now), Phase::Finished { .. })
2524            })
2525        })
2526    }
2527
2528    fn cancel_event(&mut self, node: u32, run: &AnimRun, now: Instant) {
2529        // A run that already reported `animationend` finished; it was not cancelled, and the DOM
2530        // fires only one of the two.
2531        if run.ended {
2532            return;
2533        }
2534        self.events.push(AnimEvent {
2535            node,
2536            kind: AnimEventKind::AnimationCancel,
2537            name: run.spec.name.to_string(),
2538            elapsed: run.elapsed_seconds(now).max(0.0),
2539        });
2540    }
2541
2542    pub fn tick(&mut self, now: Instant) {
2543        self.registered_samples.get_mut().clear();
2544        let mut events = Vec::new();
2545        for (&node, runs) in self.anims.iter_mut() {
2546            for run in runs.iter_mut() {
2547                if run.pending {
2548                    run.pending = false;
2549                    run.start = now;
2550                    if run.paused_at.is_some() {
2551                        run.paused_at = Some(now);
2552                    }
2553                }
2554                let phase = run.phase(now);
2555                if !run.started && !matches!(phase, Phase::Delayed) {
2556                    run.started = true;
2557                    events.push(AnimEvent {
2558                        node,
2559                        kind: AnimEventKind::AnimationStart,
2560                        name: run.spec.name.to_string(),
2561                        elapsed: run.spec.active_time(Duration::ZERO).as_secs_f32(),
2562                    });
2563                }
2564                if !run.ended && matches!(phase, Phase::Finished { .. }) {
2565                    run.ended = true;
2566                    events.push(AnimEvent {
2567                        node,
2568                        kind: AnimEventKind::AnimationEnd,
2569                        name: run.spec.name.to_string(),
2570                        elapsed: run
2571                            .spec
2572                            .total()
2573                            .map(|t| run.spec.active_time(t).as_secs_f32())
2574                            .unwrap_or(0.0),
2575                    });
2576                }
2577            }
2578        }
2579        self.events.append(&mut events);
2580    }
2581
2582    pub fn take_events(&mut self) -> Vec<AnimEvent> {
2583        std::mem::take(&mut self.events)
2584    }
2585
2586    pub fn moving_nodes(&self, now: Instant) -> impl Iterator<Item = u32> + '_ {
2587        let tracks = self
2588            .nodes
2589            .iter()
2590            .filter(move |(_, tracks)| tracks.iter().any(|t| !t.finished(now)))
2591            .map(|(&node, _)| node);
2592        let runs = self
2593            .anims
2594            .iter()
2595            .filter(move |(_, runs)| {
2596                runs.iter().any(|run| match run.phase(now) {
2597                    Phase::Finished { .. } => false,
2598                    Phase::Delayed | Phase::Running { .. } => run.paused_at.is_none(),
2599                })
2600            })
2601            .map(|(&node, _)| node);
2602        let timeline = self.timeline_ms(now);
2603        let scripts = self
2604            .scripts
2605            .iter()
2606            .filter(move |(_, list)| list.iter().any(|a| a.running(timeline)))
2607            .map(|(&node, _)| node);
2608        tracks.chain(runs).chain(scripts)
2609    }
2610
2611    pub fn any_animation(&self, now: Instant) -> bool {
2612        let css = self
2613            .anims
2614            .values()
2615            .flatten()
2616            .any(|run| match run.phase(now) {
2617                Phase::Finished { .. } => false,
2618                Phase::Delayed | Phase::Running { .. } => run.paused_at.is_none(),
2619            });
2620        css || {
2621            let timeline = self.timeline_ms(now);
2622            self.scripts.values().flatten().any(|a| a.running(timeline))
2623        }
2624    }
2625
2626    pub fn animated_extras(&self, node: u32, now: Instant) -> Option<crate::Extras> {
2627        self.registered_overlay(node, now)
2628            .map(|sample| sample.1.clone())
2629    }
2630
2631    fn registered_overlay(
2632        &self,
2633        node: u32,
2634        now: Instant,
2635    ) -> Option<Rc<(StyleRefinement, crate::Extras)>> {
2636        if let Some((at, sample)) = self.registered_samples.borrow().get(&node) {
2637            if *at == now {
2638                return Some(sample.clone());
2639            }
2640        }
2641        let runs = self.anims.get(&node)?;
2642        let mut context = None;
2643        let mut samples = Vec::new();
2644        for run in runs {
2645            let Some(scope) = &run.custom_context else {
2646                continue;
2647            };
2648            let Some(progress) = run.paint_progress(now) else {
2649                continue;
2650            };
2651            for registration in &scope.registrations {
2652                if scope.important_custom.contains(&registration.name) {
2653                    continue;
2654                }
2655                let declares = |step: &crate::Keyframe| {
2656                    scope.keyframe_value(step, &registration.name).is_some()
2657                };
2658                let Some(segment) = run.frames.segment_steps(&declares, progress) else {
2659                    continue;
2660                };
2661                let implicit = scope
2662                    .vars
2663                    .get(&registration.name)
2664                    .and_then(crate::registered::percentage)
2665                    .unwrap_or(registration.initial);
2666                let from = segment
2667                    .from
2668                    .and_then(|step| scope.keyframe_value(step, &registration.name))
2669                    .unwrap_or(implicit);
2670                let to = segment
2671                    .to
2672                    .and_then(|step| scope.keyframe_value(step, &registration.name))
2673                    .unwrap_or(implicit);
2674                let t = segment
2675                    .easing
2676                    .unwrap_or(run.spec.easing)
2677                    .eval(segment.t.clamp(0., 1.));
2678                samples.push((registration.name.clone(), from + (to - from) * t));
2679                context = Some(scope);
2680            }
2681        }
2682        context.map(|scope| {
2683            let sample = Rc::new(scope.sample(&samples));
2684            self.registered_samples
2685                .borrow_mut()
2686                .insert(node, (now, sample.clone()));
2687            sample
2688        })
2689    }
2690
2691    fn animation_overlay(
2692        &self,
2693        node: u32,
2694        base: &StyleRefinement,
2695        now: Instant,
2696    ) -> Option<StyleRefinement> {
2697        let runs = self.anims.get(&node)?;
2698        let mut out = self
2699            .registered_overlay(node, now)
2700            .map(|sample| sample.0.clone());
2701        for run in runs {
2702            let progress = match run.phase(now) {
2703                Phase::Running { progress, .. } => progress,
2704                Phase::Delayed => {
2705                    if !matches!(run.spec.fill, FillMode::Backwards | FillMode::Both) {
2706                        continue;
2707                    }
2708                    run.spec.phase(run.spec.delay.wait()).progress_or(0.0)
2709                }
2710                Phase::Finished { progress } => {
2711                    if !matches!(run.spec.fill, FillMode::Forwards | FillMode::Both) {
2712                        continue;
2713                    }
2714                    progress
2715                }
2716            };
2717            let r = out.get_or_insert_with(StyleRefinement::default);
2718            let keywords = self.keywords.contains(&node);
2719            apply_keyframes(r, base, &run.frames, &run.spec, progress, keywords);
2720        }
2721        out
2722    }
2723}
2724
2725impl Phase {
2726    fn progress_or(self, default: f32) -> f32 {
2727        match self {
2728            Phase::Running { progress, .. } | Phase::Finished { progress } => progress,
2729            Phase::Delayed => default,
2730        }
2731    }
2732}
2733
2734fn apply_keyframes(
2735    out: &mut StyleRefinement,
2736    base: &StyleRefinement,
2737    frames: &Keyframes,
2738    spec: &AnimationSpec,
2739    progress: f32,
2740    keywords: bool,
2741) {
2742    for property in TransitionProperty::keyframed() {
2743        let declares: &dyn Fn(&StyleRefinement) -> bool =
2744            &|r: &StyleRefinement| slot_of(r, &property) != Slot::Missing;
2745        let Some(segment) = frames.segment(declares, progress) else {
2746            continue;
2747        };
2748        // Needed for Tailwind's `pulse` (`50% { opacity: .5 }` only): without the fallback both
2749        // ends are unset and the animation sits at 0.5.
2750        let implicit = || match slot_of(base, &property) {
2751            Slot::Missing => initial(&property).map_or(Slot::Missing, Slot::Value),
2752            slot => slot,
2753        };
2754        let from = segment
2755            .from
2756            .map(|k| slot_of(&k.style, &property))
2757            .unwrap_or_else(implicit);
2758        let to = segment
2759            .to
2760            .map(|k| slot_of(&k.style, &property))
2761            .unwrap_or_else(implicit);
2762        let (from, to) = size_pair(from, to, &property, keywords).unwrap_or((from, to));
2763        let (Slot::Value(a), Slot::Value(b)) = (from, to) else {
2764            if let Slot::Value(v) = from {
2765                install(out, base, &property, v);
2766            } else if let Slot::Value(v) = to {
2767                install(out, base, &property, v);
2768            }
2769            continue;
2770        };
2771        let Some((a, b)) = unify(a, b) else {
2772            install(out, base, &property, if segment.t < 0.5 { a } else { b });
2773            continue;
2774        };
2775        let easing = segment.easing.unwrap_or(spec.easing);
2776        install(
2777            out,
2778            base,
2779            &property,
2780            lerp(a, b, easing.eval(segment.t.clamp(0.0, 1.0))),
2781        );
2782    }
2783}
2784
2785#[cfg(test)]
2786mod border_colors_regressions {
2787    use super::*;
2788    #[test]
2789    fn transition_interpolates_each_border_side_and_uniform_shorthand_resets_it() {
2790        let mut before = StyleRefinement::default();
2791        before.border_color = Some(gpui::red());
2792        before.vn_border_colors.left = Some(Some(gpui::blue()));
2793        let mut after = StyleRefinement::default();
2794        after.border_color = Some(gpui::green());
2795        let (Slot::Value(a), Slot::Value(b)) = (
2796            slot_of(&before, &TransitionProperty::BorderColor),
2797            slot_of(&after, &TransitionProperty::BorderColor),
2798        ) else {
2799            panic!("border endpoints missing")
2800        };
2801        let (a, b) = unify(a, b).expect("uniform and per-side colours interpolate");
2802        let mut overlay = StyleRefinement::default();
2803        install(
2804            &mut overlay,
2805            &after,
2806            &TransitionProperty::BorderColor,
2807            lerp(a, b, 0.5),
2808        );
2809        assert_ne!(overlay.vn_border_colors.left, overlay.vn_border_colors.top);
2810        install(
2811            &mut overlay,
2812            &before,
2813            &TransitionProperty::BorderColor,
2814            Animatable::Color(gpui::green()),
2815        );
2816        assert_eq!(overlay.vn_border_colors.left, Some(None));
2817        clear(&mut overlay, &TransitionProperty::BorderColor);
2818        assert_eq!(overlay.vn_border_colors.left, None);
2819        assert_eq!(overlay.border_color, None);
2820    }
2821}
2822
2823#[cfg(test)]
2824mod size_interpolation {
2825    use super::*;
2826    use gpui::{px, VnCalcSize, VnSizeBasis};
2827    use std::rc::Rc;
2828
2829    fn computed(style: &str) -> ComputedStates {
2830        let mut diagnostics = Vec::new();
2831        let inline = crate::parse_inline_style(
2832            &format!("{style}; transition: height 1s linear"),
2833            &mut diagnostics,
2834        );
2835        let mut base = inline.refinement.map(|r| (*r).clone()).unwrap_or_default();
2836        let transitions = inline.transitions.map(|t| (*t).clone()).unwrap_or_default();
2837        for (name, value) in inline.dynamic.iter() {
2838            crate::mapper::apply_dynamic(
2839                name,
2840                value,
2841                &crate::Vars::default(),
2842                &crate::Env::default(),
2843                &mut base,
2844                &mut crate::Extras::default(),
2845                &mut diagnostics,
2846            );
2847        }
2848        assert!(diagnostics.is_empty(), "{diagnostics:?}");
2849        ComputedStates {
2850            base: Rc::new(base),
2851            transitions: Rc::new(transitions),
2852            ..Default::default()
2853        }
2854    }
2855
2856    fn height_at(keywords: bool, from: &str, to: &str, ms: u64) -> Option<Length> {
2857        let mut a = Animator::new();
2858        a.set_interpolate_keywords(1, keywords);
2859        let now = Instant::now();
2860        a.on_computed(1, Some(&computed(from)), &computed(to), now);
2861        a.overlay(
2862            1,
2863            &StyleRefinement::default(),
2864            now + Duration::from_millis(ms),
2865        )
2866        .and_then(|r| r.size.height)
2867    }
2868
2869    fn auto_times(scale: f32, pixels: f32) -> Option<Length> {
2870        Some(Length::VnCalcSize(VnCalcSize {
2871            basis: VnSizeBasis::Auto,
2872            scale,
2873            offset: px(pixels).into(),
2874        }))
2875    }
2876
2877    #[test]
2878    fn allow_keywords_interpolates_auto_with_a_length() {
2879        assert_eq!(
2880            height_at(true, "height: 0px", "height: auto", 250),
2881            auto_times(0.25, 0.)
2882        );
2883        assert_eq!(
2884            height_at(true, "height: auto", "height: 40px", 250),
2885            auto_times(0.75, 10.)
2886        );
2887        assert_eq!(
2888            height_at(true, "height: 10px", "width: 1px", 500),
2889            auto_times(0.5, 5.),
2890            "an unset height is auto"
2891        );
2892    }
2893
2894    #[test]
2895    fn numeric_only_snaps_between_auto_and_a_length() {
2896        assert_eq!(height_at(false, "height: 0px", "height: auto", 250), None);
2897    }
2898
2899    #[test]
2900    fn calc_size_interpolates_without_allow_keywords() {
2901        assert_eq!(
2902            height_at(false, "height: 0px", "height: calc-size(auto, size)", 500),
2903            auto_times(0.5, 0.)
2904        );
2905        assert_eq!(
2906            height_at(
2907                false,
2908                "height: calc-size(auto, size + 20px)",
2909                "height: 100px",
2910                500
2911            ),
2912            auto_times(0.5, 60.)
2913        );
2914        assert_eq!(
2915            height_at(
2916                false,
2917                "height: calc-size(auto, size * 0.5)",
2918                "height: auto",
2919                500
2920            ),
2921            auto_times(0.75, 0.)
2922        );
2923        assert_eq!(
2924            height_at(false, "height: 50%", "height: calc-size(auto, size)", 500),
2925            Some(Length::VnCalcSize(VnCalcSize {
2926                basis: VnSizeBasis::Auto,
2927                scale: 0.5,
2928                offset: DefiniteLength::Fraction(0.25),
2929            }))
2930        );
2931    }
2932
2933    #[test]
2934    fn different_bases_do_not_interpolate() {
2935        assert_eq!(
2936            height_at(
2937                true,
2938                "height: calc-size(fit-content, size)",
2939                "height: calc-size(min-content, size)",
2940                500
2941            ),
2942            None
2943        );
2944    }
2945
2946    #[test]
2947    fn a_script_animation_to_auto_interpolates_under_allow_keywords() {
2948        let frames = [
2949            ScriptFrame {
2950                offset: 0.,
2951                easing: None,
2952                decls: vec![("height".into(), "0px".into())],
2953            },
2954            ScriptFrame {
2955                offset: 1.,
2956                easing: None,
2957                decls: vec![("height".into(), "auto".into())],
2958            },
2959        ];
2960        let (frames, notes) =
2961            script_keyframes(&frames, &crate::Vars::default(), &crate::Env::default());
2962        assert!(notes.diagnostics.is_empty(), "{notes:?}");
2963        let mut a = Animator::new();
2964        let t0 = Instant::now();
2965        a.set_timeline_origin(t0);
2966        a.set_interpolate_keywords(7, true);
2967        a.script_set(
2968            1,
2969            7,
2970            frames,
2971            ScriptTiming {
2972                duration: 1000.,
2973                ..ScriptTiming::default()
2974            },
2975        );
2976        a.script_clock(
2977            1,
2978            ScriptClock {
2979                start: Some(0.),
2980                hold: None,
2981                rate: 1.,
2982            },
2983        );
2984        let height = a
2985            .overlay(
2986                7,
2987                &StyleRefinement::default(),
2988                t0 + Duration::from_millis(400),
2989            )
2990            .and_then(|r| r.size.height);
2991        assert_eq!(height, auto_times(0.4, 0.));
2992    }
2993}