Skip to main content

sk_css/
keyframes.rs

1//! `@keyframes` and `animation-*`. Keyframes compile document-wide onto the `Engine`, the
2//! `animation-*` declarations fold per element into `AnimationSpec`s, and the animator joins them.
3//! The timeline is per property: a keyframe is a stop only for the properties it declares, a
4//! missing 0% / 100% takes the element's own value, and `animation-timing-function` governs the
5//! segment starting at its keyframe.
6
7use std::rc::Rc;
8use std::time::Duration;
9
10use gpui::StyleRefinement;
11
12use crate::transition::{Delay, Easing};
13
14pub struct Keyframe {
15    pub offset: f32,
16    pub easing: Option<Easing>,
17    pub style: Rc<StyleRefinement>,
18    /// `var()`-composed declarations: the block is document-scoped but custom properties are per
19    /// element, so they are substituted by `Engine::keyframes_for` when a run starts.
20    pub dynamic: Option<Rc<crate::mapper::Decls>>,
21    pub custom: Option<Rc<crate::mapper::Decls>>,
22}
23
24pub struct Keyframes {
25    pub steps: Vec<Keyframe>,
26    pub dynamic: bool,
27}
28
29#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
30pub enum Direction {
31    #[default]
32    Normal,
33    Reverse,
34    Alternate,
35    AlternateReverse,
36}
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
39pub enum FillMode {
40    #[default]
41    None,
42    Forwards,
43    Backwards,
44    Both,
45}
46
47#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
48pub enum PlayState {
49    #[default]
50    Running,
51    Paused,
52}
53
54#[derive(Clone, Debug, PartialEq)]
55pub struct AnimationSpec {
56    pub name: Rc<str>,
57    pub duration: Duration,
58    pub delay: Delay,
59    pub iterations: f32,
60    pub direction: Direction,
61    pub fill: FillMode,
62    pub easing: Easing,
63    pub play_state: PlayState,
64}
65
66impl AnimationSpec {
67    pub fn is_inert(&self) -> bool {
68        self.name.is_empty() || (self.duration.is_zero() && self.delay.is_zero())
69    }
70
71    pub fn total(&self) -> Option<Duration> {
72        if !self.iterations.is_finite() {
73            return None;
74        }
75        // A count that carries the end past what a `Duration` holds never ends as far as anyone
76        // watching can tell; `mul_f32` would panic.
77        let run = self.duration.as_secs_f64() * self.iterations.max(0.0) as f64;
78        let run = Duration::try_from_secs_f64(run).ok()?;
79        self.delay.end_after(run)
80    }
81
82    /// Time spent in the active interval, counting a negative delay as already run.
83    pub fn active_time(&self, elapsed: Duration) -> Duration {
84        (elapsed + self.delay.skip()).saturating_sub(self.delay.wait())
85    }
86
87    pub fn phase(&self, elapsed: Duration) -> Phase {
88        let Some(running) = self.delay.active(elapsed) else {
89            return Phase::Delayed;
90        };
91        if self.duration.is_zero() {
92            return Phase::Finished {
93                progress: self.final_progress(),
94            };
95        }
96        let raw = running.as_secs_f64() / self.duration.as_secs_f64();
97        if raw >= self.iterations as f64 {
98            return Phase::Finished {
99                progress: self.final_progress(),
100            };
101        }
102        let iteration = raw.floor() as f32;
103        Phase::Running {
104            iteration,
105            progress: self.direct(iteration, (raw - raw.floor()) as f32),
106        }
107    }
108
109    fn final_progress(&self) -> f32 {
110        let last = if self.iterations.is_finite() {
111            self.iterations.max(0.0)
112        } else {
113            1.0
114        };
115        if last == 0.0 {
116            return self.direct(0.0, 0.0);
117        }
118        if last.fract() == 0.0 {
119            self.direct(last - 1.0, 1.0)
120        } else {
121            self.direct(last.floor(), last.fract())
122        }
123    }
124
125    fn direct(&self, iteration: f32, progress: f32) -> f32 {
126        let odd = (iteration as i64) % 2 != 0;
127        let reverse = match self.direction {
128            Direction::Normal => false,
129            Direction::Reverse => true,
130            Direction::Alternate => odd,
131            Direction::AlternateReverse => !odd,
132        };
133        if reverse {
134            1.0 - progress
135        } else {
136            progress
137        }
138    }
139}
140
141#[derive(Clone, Copy, Debug, PartialEq)]
142pub enum Phase {
143    Delayed,
144    Running { iteration: f32, progress: f32 },
145    Finished { progress: f32 },
146}
147
148impl Keyframes {
149    pub fn segment<'a>(
150        &'a self,
151        declares: &dyn Fn(&StyleRefinement) -> bool,
152        progress: f32,
153    ) -> Option<Segment<'a>> {
154        self.segment_steps(&|step| declares(&step.style), progress)
155    }
156
157    pub(crate) fn segment_steps<'a>(
158        &'a self,
159        declares: &dyn Fn(&Keyframe) -> bool,
160        progress: f32,
161    ) -> Option<Segment<'a>> {
162        let mut before: Option<&Keyframe> = None;
163        let mut after: Option<&Keyframe> = None;
164        for step in self.steps.iter().filter(|s| declares(s)) {
165            if step.offset <= progress {
166                before = Some(step);
167            } else {
168                after = Some(step);
169                break;
170            }
171        }
172        let span = |a: f32, b: f32| {
173            let width = b - a;
174            if width > 0.0 {
175                ((progress - a) / width).clamp(0.0, 1.0)
176            } else {
177                1.0
178            }
179        };
180        match (before, after) {
181            (None, None) => None,
182            (None, Some(to)) => Some(Segment {
183                from: None,
184                to: Some(to),
185                t: span(0.0, to.offset),
186                easing: None,
187            }),
188            // Nothing after the last declared keyframe: interpolate to itself, so `fill-mode:
189            // forwards` holds the end value instead of snapping back to the element's own.
190            (Some(from), None) if from.offset >= 1.0 => Some(Segment {
191                from: Some(from),
192                to: Some(from),
193                t: 1.0,
194                easing: from.easing,
195            }),
196            (Some(from), None) => Some(Segment {
197                from: Some(from),
198                to: None,
199                t: span(from.offset, 1.0),
200                easing: from.easing,
201            }),
202            (Some(from), Some(to)) => Some(Segment {
203                from: Some(from),
204                to: Some(to),
205                t: span(from.offset, to.offset),
206                easing: from.easing,
207            }),
208        }
209    }
210}
211
212/// `animation-*` longhands without a list: a lone `animation-play-state: paused` or
213/// `animation-fill-mode: forwards` (reka-ui's `Presence` writes it) must not delete the animation
214/// the sheet started, so it applies as a patch over the winning list.
215#[derive(Clone, Debug, Default, PartialEq)]
216pub struct AnimationPatch {
217    pub duration: Option<Duration>,
218    pub delay: Option<Delay>,
219    pub easing: Option<Easing>,
220    pub iterations: Option<f32>,
221    pub direction: Option<Direction>,
222    pub fill: Option<FillMode>,
223    pub play_state: Option<PlayState>,
224    // A later animation-name must not reset an earlier duration, and duration lists must keep
225    // cycling even when a later rule changes names.
226    #[doc(hidden)]
227    pub declarations: Option<Rc<AnimationDeclarations>>,
228}
229
230impl AnimationPatch {
231    pub fn is_empty(&self) -> bool {
232        *self == AnimationPatch::default()
233    }
234
235    pub fn apply_over(&self, into: &mut AnimationPatch) {
236        if self.duration.is_some() {
237            into.duration = self.duration;
238        }
239        if self.delay.is_some() {
240            into.delay = self.delay;
241        }
242        if self.easing.is_some() {
243            into.easing = self.easing;
244        }
245        if self.iterations.is_some() {
246            into.iterations = self.iterations;
247        }
248        if self.direction.is_some() {
249            into.direction = self.direction;
250        }
251        if self.fill.is_some() {
252            into.fill = self.fill;
253        }
254        if self.play_state.is_some() {
255            into.play_state = self.play_state;
256        }
257        if let Some(declarations) = &self.declarations {
258            let mut merged = into.declarations.as_deref().cloned().unwrap_or_default();
259            merged.merge(declarations);
260            into.declarations = Some(Rc::new(merged));
261        } else if self.duration.is_some()
262            || self.delay.is_some()
263            || self.easing.is_some()
264            || self.iterations.is_some()
265            || self.direction.is_some()
266            || self.fill.is_some()
267            || self.play_state.is_some()
268        {
269            let legacy = AnimationCollector {
270                durations: self.duration.map(|value| vec![value]),
271                delays: self.delay.map(|value| vec![value]),
272                easings: self.easing.map(|value| vec![value]),
273                iterations: self.iterations.map(|value| vec![value]),
274                directions: self.direction.map(|value| vec![value]),
275                fills: self.fill.map(|value| vec![value]),
276                play_states: self.play_state.map(|value| vec![value]),
277                seen: true,
278                ..Default::default()
279            };
280            let mut merged = into.declarations.as_deref().cloned().unwrap_or_default();
281            merged.merge(&legacy);
282            into.declarations = Some(Rc::new(merged));
283        }
284    }
285
286    pub(crate) fn computed_list(&self) -> Option<Vec<AnimationSpec>> {
287        self.declarations
288            .as_ref()
289            .map(|declarations| declarations.specs())
290    }
291
292    pub fn apply(&self, spec: &mut AnimationSpec) {
293        if let Some(v) = self.duration {
294            spec.duration = v;
295        }
296        if let Some(v) = self.delay {
297            spec.delay = v;
298        }
299        if let Some(v) = self.easing {
300            spec.easing = v;
301        }
302        if let Some(v) = self.iterations {
303            spec.iterations = v;
304        }
305        if let Some(v) = self.direction {
306            spec.direction = v;
307        }
308        if let Some(v) = self.fill {
309            spec.fill = v;
310        }
311        if let Some(v) = self.play_state {
312            spec.play_state = v;
313        }
314    }
315}
316
317pub struct Segment<'a> {
318    pub from: Option<&'a Keyframe>,
319    pub to: Option<&'a Keyframe>,
320    pub t: f32,
321    pub easing: Option<Easing>,
322}
323
324#[doc(hidden)]
325#[derive(Clone, Debug, Default, PartialEq)]
326pub struct AnimationDeclarations {
327    names: Option<Vec<Rc<str>>>,
328    durations: Option<Vec<Duration>>,
329    delays: Option<Vec<Delay>>,
330    easings: Option<Vec<Easing>>,
331    iterations: Option<Vec<f32>>,
332    directions: Option<Vec<Direction>>,
333    fills: Option<Vec<FillMode>>,
334    play_states: Option<Vec<PlayState>>,
335    seen: bool,
336    named: bool,
337}
338
339pub(crate) type AnimationCollector = AnimationDeclarations;
340
341impl AnimationDeclarations {
342    pub(crate) fn take(
343        &mut self,
344        p: &lightningcss::properties::Property,
345        diagnostics: &mut Vec<String>,
346    ) -> bool {
347        use lightningcss::properties::animation as a;
348        use lightningcss::properties::Property as P;
349
350        fn name_of(n: &a::AnimationName) -> Rc<str> {
351            match n {
352                a::AnimationName::None => "".into(),
353                a::AnimationName::Ident(i) => i.0.as_ref().into(),
354                a::AnimationName::String(s) => s.as_ref().into(),
355            }
356        }
357        fn count_of(c: &a::AnimationIterationCount) -> f32 {
358            match c {
359                a::AnimationIterationCount::Infinite => f32::INFINITY,
360                a::AnimationIterationCount::Number(n) => n.max(0.0),
361            }
362        }
363        fn dir_of(d: &a::AnimationDirection) -> Direction {
364            match d {
365                a::AnimationDirection::Normal => Direction::Normal,
366                a::AnimationDirection::Reverse => Direction::Reverse,
367                a::AnimationDirection::Alternate => Direction::Alternate,
368                a::AnimationDirection::AlternateReverse => Direction::AlternateReverse,
369            }
370        }
371        fn fill_of(f: &a::AnimationFillMode) -> FillMode {
372            match f {
373                a::AnimationFillMode::None => FillMode::None,
374                a::AnimationFillMode::Forwards => FillMode::Forwards,
375                a::AnimationFillMode::Backwards => FillMode::Backwards,
376                a::AnimationFillMode::Both => FillMode::Both,
377            }
378        }
379        fn play_of(s: &a::AnimationPlayState) -> PlayState {
380            match s {
381                a::AnimationPlayState::Running => PlayState::Running,
382                a::AnimationPlayState::Paused => PlayState::Paused,
383            }
384        }
385
386        match p {
387            P::Animation(list, _) => {
388                self.seen = true;
389                self.named = true;
390                self.names = Some(list.iter().map(|e| name_of(&e.name)).collect());
391                self.durations = Some(
392                    list.iter()
393                        .map(|e| {
394                            crate::transition::duration_of(
395                                &e.duration,
396                                "animation-duration",
397                                diagnostics,
398                            )
399                        })
400                        .collect(),
401                );
402                self.delays = Some(
403                    list.iter()
404                        .map(|e| {
405                            crate::transition::delay_of(&e.delay, "animation-delay", diagnostics)
406                        })
407                        .collect(),
408                );
409                self.easings = Some(
410                    list.iter()
411                        .map(|e| crate::transition::easing_of(&e.timing_function, diagnostics))
412                        .collect(),
413                );
414                self.iterations = Some(list.iter().map(|e| count_of(&e.iteration_count)).collect());
415                self.directions = Some(list.iter().map(|e| dir_of(&e.direction)).collect());
416                self.fills = Some(list.iter().map(|e| fill_of(&e.fill_mode)).collect());
417                self.play_states = Some(list.iter().map(|e| play_of(&e.play_state)).collect());
418                if list
419                    .iter()
420                    .any(|e| !matches!(e.timeline, a::AnimationTimeline::Auto))
421                {
422                    crate::mapper::once(
423                        diagnostics,
424                        "`animation-timeline` is not supported (v1) — scroll/view timelines have \
425                         no clock here; the animation runs on the document timeline instead"
426                            .into(),
427                    );
428                }
429                true
430            }
431            P::AnimationName(list, _) => {
432                self.seen = true;
433                self.named = true;
434                self.names = Some(list.iter().map(name_of).collect());
435                true
436            }
437            P::AnimationDuration(list, _) => {
438                self.seen = true;
439                self.durations = Some(
440                    list.iter()
441                        .map(|t| {
442                            crate::transition::duration_of(t, "animation-duration", diagnostics)
443                        })
444                        .collect(),
445                );
446                true
447            }
448            P::AnimationDelay(list, _) => {
449                self.seen = true;
450                self.delays = Some(
451                    list.iter()
452                        .map(|t| crate::transition::delay_of(t, "animation-delay", diagnostics))
453                        .collect(),
454                );
455                true
456            }
457            P::AnimationTimingFunction(list, _) => {
458                self.seen = true;
459                self.easings = Some(
460                    list.iter()
461                        .map(|e| crate::transition::easing_of(e, diagnostics))
462                        .collect(),
463                );
464                true
465            }
466            P::AnimationIterationCount(list, _) => {
467                self.seen = true;
468                self.iterations = Some(list.iter().map(count_of).collect());
469                true
470            }
471            P::AnimationDirection(list, _) => {
472                self.seen = true;
473                self.directions = Some(list.iter().map(dir_of).collect());
474                true
475            }
476            P::AnimationFillMode(list, _) => {
477                self.seen = true;
478                self.fills = Some(list.iter().map(fill_of).collect());
479                true
480            }
481            P::AnimationPlayState(list, _) => {
482                self.seen = true;
483                self.play_states = Some(list.iter().map(play_of).collect());
484                true
485            }
486            P::AnimationTimeline(..) => {
487                self.seen = true;
488                crate::mapper::once(
489                    diagnostics,
490                    "`animation-timeline` is not supported (v1) — scroll/view timelines have no \
491                     clock here; the animation runs on the document timeline instead"
492                        .into(),
493                );
494                true
495            }
496            P::Unparsed(u) if u.property_id.name().starts_with("animation") => {
497                self.seen = true;
498                crate::mapper::once(
499                    diagnostics,
500                    format!(
501                        "unresolved value for {} (var()/env() in animations is not resolved yet, \
502                         v1)",
503                        u.property_id.name()
504                    ),
505                );
506                true
507            }
508            _ => false,
509        }
510    }
511
512    pub(crate) fn merge(&mut self, later: &Self) {
513        macro_rules! field {
514            ($field:ident) => {
515                if later.$field.is_some() {
516                    self.$field = later.$field.clone();
517                }
518            };
519        }
520        field!(names);
521        field!(durations);
522        field!(delays);
523        field!(easings);
524        field!(iterations);
525        field!(directions);
526        field!(fills);
527        field!(play_states);
528        self.seen |= later.seen;
529        self.named |= later.named;
530    }
531
532    pub(crate) fn from_specs(specs: &[AnimationSpec]) -> Self {
533        Self {
534            names: Some(specs.iter().map(|spec| spec.name.clone()).collect()),
535            durations: Some(specs.iter().map(|spec| spec.duration).collect()),
536            delays: Some(specs.iter().map(|spec| spec.delay).collect()),
537            easings: Some(specs.iter().map(|spec| spec.easing).collect()),
538            iterations: Some(specs.iter().map(|spec| spec.iterations).collect()),
539            directions: Some(specs.iter().map(|spec| spec.direction).collect()),
540            fills: Some(specs.iter().map(|spec| spec.fill).collect()),
541            play_states: Some(specs.iter().map(|spec| spec.play_state).collect()),
542            seen: true,
543            named: true,
544        }
545    }
546
547    pub(crate) fn finish(self) -> (Option<Vec<AnimationSpec>>, Option<AnimationPatch>) {
548        if !self.seen {
549            return (None, None);
550        }
551        let list = self.named.then(|| self.specs());
552        let patch = AnimationPatch {
553            duration: self
554                .durations
555                .as_ref()
556                .and_then(|list| list.first().copied()),
557            delay: self.delays.as_ref().and_then(|list| list.first().copied()),
558            easing: self.easings.as_ref().and_then(|list| list.first().copied()),
559            iterations: self
560                .iterations
561                .as_ref()
562                .and_then(|list| list.first().copied()),
563            direction: self
564                .directions
565                .as_ref()
566                .and_then(|list| list.first().copied()),
567            fill: self.fills.as_ref().and_then(|list| list.first().copied()),
568            play_state: self
569                .play_states
570                .as_ref()
571                .and_then(|list| list.first().copied()),
572            declarations: Some(Rc::new(self)),
573        };
574        (list, Some(patch))
575    }
576
577    fn specs(&self) -> Vec<AnimationSpec> {
578        let names = self.names.as_deref().unwrap_or_default();
579        let mut out = Vec::with_capacity(names.len());
580        for (i, name) in names.iter().enumerate() {
581            out.push(AnimationSpec {
582                name: name.clone(),
583                duration: cycle(&self.durations, i, Duration::ZERO),
584                delay: cycle(&self.delays, i, Delay::ZERO),
585                iterations: cycle(&self.iterations, i, 1.0),
586                direction: cycle(&self.directions, i, Direction::Normal),
587                fill: cycle(&self.fills, i, FillMode::None),
588                easing: cycle(&self.easings, i, Easing::Ease),
589                play_state: cycle(&self.play_states, i, PlayState::Running),
590            });
591        }
592        out
593    }
594}
595
596fn cycle<T: Copy>(list: &Option<Vec<T>>, i: usize, default: T) -> T {
597    match list {
598        Some(l) if !l.is_empty() => l[i % l.len()],
599        _ => default,
600    }
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606
607    fn spec(iterations: f32, direction: Direction) -> AnimationSpec {
608        AnimationSpec {
609            name: "spin".into(),
610            duration: Duration::from_millis(1000),
611            delay: Delay::ZERO,
612            iterations,
613            direction,
614            fill: FillMode::None,
615            easing: Easing::Linear,
616            play_state: PlayState::Running,
617        }
618    }
619
620    #[test]
621    fn direction_reverses_the_right_iterations() {
622        let alt = spec(4.0, Direction::Alternate);
623        assert_eq!(
624            alt.phase(Duration::from_millis(250)),
625            Phase::Running {
626                iteration: 0.0,
627                progress: 0.25
628            }
629        );
630        assert_eq!(
631            alt.phase(Duration::from_millis(1250)),
632            Phase::Running {
633                iteration: 1.0,
634                progress: 0.75
635            }
636        );
637        assert_eq!(
638            alt.phase(Duration::from_millis(2250)),
639            Phase::Running {
640                iteration: 2.0,
641                progress: 0.25
642            }
643        );
644
645        let rev = spec(2.0, Direction::Reverse);
646        assert_eq!(
647            rev.phase(Duration::from_millis(250)),
648            Phase::Running {
649                iteration: 0.0,
650                progress: 0.75
651            }
652        );
653
654        let altrev = spec(2.0, Direction::AlternateReverse);
655        assert_eq!(
656            altrev.phase(Duration::from_millis(250)),
657            Phase::Running {
658                iteration: 0.0,
659                progress: 0.75
660            }
661        );
662        assert_eq!(
663            altrev.phase(Duration::from_millis(1250)),
664            Phase::Running {
665                iteration: 1.0,
666                progress: 0.25
667            }
668        );
669    }
670
671    #[test]
672    fn the_end_value_is_the_end_of_the_last_iteration() {
673        let alt = spec(2.0, Direction::Alternate);
674        assert_eq!(
675            alt.phase(Duration::from_millis(5000)),
676            Phase::Finished { progress: 0.0 }
677        );
678        let alt3 = spec(3.0, Direction::Alternate);
679        assert_eq!(
680            alt3.phase(Duration::from_millis(5000)),
681            Phase::Finished { progress: 1.0 }
682        );
683        let half = spec(1.5, Direction::Normal);
684        assert_eq!(
685            half.phase(Duration::from_millis(5000)),
686            Phase::Finished { progress: 0.5 }
687        );
688    }
689
690    #[test]
691    fn an_instant_animation_rests_where_a_timed_one_does() {
692        let mut one = spec(1.0, Direction::Alternate);
693        one.duration = Duration::ZERO;
694        assert_eq!(one.phase(Duration::ZERO), Phase::Finished { progress: 1.0 });
695        let mut two = spec(2.0, Direction::Alternate);
696        two.duration = Duration::ZERO;
697        assert_eq!(two.phase(Duration::ZERO), Phase::Finished { progress: 0.0 });
698    }
699
700    #[test]
701    fn a_count_of_zero_rests_at_the_start() {
702        let none = spec(0.0, Direction::Normal);
703        assert_eq!(
704            none.phase(Duration::from_millis(10)),
705            Phase::Finished { progress: 0.0 }
706        );
707        let reversed = spec(0.0, Direction::Reverse);
708        assert_eq!(
709            reversed.phase(Duration::from_millis(10)),
710            Phase::Finished { progress: 1.0 }
711        );
712    }
713
714    #[test]
715    fn a_total_past_what_a_duration_holds_is_endless() {
716        let mut long = spec(1.0e30, Direction::Normal);
717        long.duration = Duration::from_secs(1_000_000_000);
718        assert_eq!(long.total(), None);
719    }
720
721    #[test]
722    fn infinite_never_finishes() {
723        let forever = spec(f32::INFINITY, Direction::Normal);
724        assert_eq!(forever.total(), None);
725        assert!(matches!(
726            forever.phase(Duration::from_secs(10_000)),
727            Phase::Running { .. }
728        ));
729    }
730
731    #[test]
732    fn the_delay_holds_the_animation_off() {
733        let mut s = spec(1.0, Direction::Normal);
734        s.delay = Duration::from_millis(500).into();
735        assert_eq!(s.phase(Duration::from_millis(200)), Phase::Delayed);
736        assert_eq!(
737            s.phase(Duration::from_millis(750)),
738            Phase::Running {
739                iteration: 0.0,
740                progress: 0.25
741            }
742        );
743        assert_eq!(s.total(), Some(Duration::from_millis(1500)));
744    }
745
746    #[test]
747    fn a_negative_delay_starts_part_way_through() {
748        let mut s = spec(1.0, Direction::Normal);
749        s.delay = Delay::from_secs_f64(-0.5);
750        assert_eq!(
751            s.phase(Duration::ZERO),
752            Phase::Running {
753                iteration: 0.0,
754                progress: 0.5
755            }
756        );
757        assert_eq!(s.total(), Some(Duration::from_millis(500)));
758    }
759
760    #[test]
761    fn a_property_only_stops_at_the_keyframes_that_declare_it() {
762        let mut mid = StyleRefinement::default();
763        mid.size.width = Some(gpui::px(10.0).into());
764        let mut zero = StyleRefinement::default();
765        zero.opacity = Some(0.0);
766        let mut one = StyleRefinement::default();
767        one.opacity = Some(1.0);
768
769        let frames = Keyframes {
770            steps: vec![
771                Keyframe {
772                    offset: 0.0,
773                    easing: None,
774                    style: Rc::new(zero),
775                    dynamic: None,
776                    custom: None,
777                },
778                Keyframe {
779                    offset: 0.5,
780                    easing: None,
781                    style: Rc::new(mid),
782                    dynamic: None,
783                    custom: None,
784                },
785                Keyframe {
786                    offset: 1.0,
787                    easing: None,
788                    style: Rc::new(one),
789                    dynamic: None,
790                    custom: None,
791                },
792            ],
793            dynamic: false,
794        };
795        let declares_opacity: &dyn Fn(&StyleRefinement) -> bool = &|r| r.opacity.is_some();
796        let seg = frames.segment(declares_opacity, 0.5).unwrap();
797        assert_eq!(seg.from.unwrap().offset, 0.0);
798        assert_eq!(seg.to.unwrap().offset, 1.0);
799        assert_eq!(seg.t, 0.5);
800
801        let declares_width: &dyn Fn(&StyleRefinement) -> bool = &|r| r.size.width.is_some();
802        let seg = frames.segment(declares_width, 0.75).unwrap();
803        assert_eq!(seg.from.unwrap().offset, 0.5);
804        assert!(seg.to.is_none());
805
806        let declares_height: &dyn Fn(&StyleRefinement) -> bool = &|r| r.size.height.is_some();
807        assert!(frames.segment(declares_height, 0.5).is_none());
808    }
809}