1use scheduler::Instant;
2use std::{cell::Cell, rc::Rc, time::Duration};
3
4use crate::{
5 AnyElement, App, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,
6 ParentElement, SpringAnimation, SpringConfig, SpringPlayback, SpringState, SpringTarget,
7 Window,
8};
9
10pub use easing::*;
11use smallvec::SmallVec;
12
13#[derive(Clone)]
15pub struct Animation {
16 pub duration: Duration,
18 pub oneshot: bool,
20 pub synced: bool,
22 pub easing: Rc<dyn Fn(f32) -> f32>,
25 pub max_fps: Option<f32>,
28}
29
30impl Animation {
31 pub fn new(duration: Duration) -> Self {
34 Self {
35 duration,
36 oneshot: true,
37 synced: false,
38 easing: Rc::new(linear),
39 max_fps: None,
40 }
41 }
42
43 pub fn repeat(mut self) -> Self {
45 self.oneshot = false;
46 self
47 }
48
49 pub fn repeat_synced(mut self) -> Self {
51 self.oneshot = false;
52 self.synced = true;
53 self
54 }
55
56 pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
61 self.easing = Rc::new(easing);
62 self
63 }
64
65 pub fn with_max_fps(mut self, max_fps: f32) -> Self {
70 self.max_fps = Some(max_fps);
71 self
72 }
73}
74
75pub trait AnimationExt {
83 fn with_animation(
85 self,
86 id: impl Into<ElementId>,
87 animation: Animation,
88 animator: impl Fn(Self, f32) -> Self + 'static,
89 ) -> AnimationElement<Self>
90 where
91 Self: Sized,
92 {
93 AnimationElement {
94 id: id.into(),
95 element: Some(self),
96 animator: Box::new(move |this, _, value| animator(this, value)),
97 animations: smallvec::smallvec![animation],
98 }
99 }
100
101 fn with_animations(
103 self,
104 id: impl Into<ElementId>,
105 animations: Vec<Animation>,
106 animator: impl Fn(Self, usize, f32) -> Self + 'static,
107 ) -> AnimationElement<Self>
108 where
109 Self: Sized,
110 {
111 AnimationElement {
112 id: id.into(),
113 element: Some(self),
114 animator: Box::new(animator),
115 animations: animations.into(),
116 }
117 }
118
119 fn with_spring<T>(
125 self,
126 id: impl Into<ElementId>,
127 animation: SpringAnimation<T>,
128 animator: impl FnOnce(Self, T::Output) -> Self + 'static,
129 ) -> SpringAnimationElement<Self>
130 where
131 Self: Sized,
132 T: SpringTarget,
133 T::Output: 'static,
134 {
135 let SpringAnimation {
136 config,
137 target,
138 epsilon,
139 initial,
140 playback,
141 } = animation;
142 let scalar_target = target.target();
143 SpringAnimationElement {
144 id: id.into(),
145 element: Some(self),
146 config,
147 target: scalar_target,
148 epsilon,
149 initial,
150 playback,
151 animator: Some(Box::new(move |this, value| {
152 animator(this, target.resolve(value))
153 })),
154 }
155 }
156}
157
158impl<E: IntoElement + 'static> AnimationExt for E {}
159
160pub struct AnimationElement<E> {
162 id: ElementId,
163 element: Option<E>,
164 animations: SmallVec<[Animation; 1]>,
165 animator: Box<dyn Fn(E, usize, f32) -> E + 'static>,
166}
167
168pub struct SpringAnimationElement<E> {
170 id: ElementId,
171 element: Option<E>,
172 config: SpringConfig,
173 target: f32,
174 epsilon: f32,
175 initial: Option<f32>,
176 playback: SpringPlayback,
177 animator: Option<Box<dyn FnOnce(E, f32) -> E + 'static>>,
178}
179
180impl<E: ParentElement> ParentElement for SpringAnimationElement<E> {
181 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
182 let Some(element) = &mut self.element else {
183 return;
184 };
185
186 element.extend(elements);
187 }
188}
189
190impl<E> SpringAnimationElement<E> {
191 pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> SpringAnimationElement<E> {
194 self.element = self.element.map(f);
195 self
196 }
197}
198
199impl<E: ParentElement> ParentElement for AnimationElement<E> {
200 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
201 let Some(element) = &mut self.element else {
202 return;
203 };
204
205 element.extend(elements);
206 }
207}
208
209impl<E> AnimationElement<E> {
210 pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> AnimationElement<E> {
213 self.element = self.element.map(f);
214 self
215 }
216}
217
218struct AnimationState {
219 start: Instant,
220 animation_ix: usize,
221 delayed_frame_pending: Rc<Cell<bool>>,
224}
225
226struct SpringElementState {
227 spring: SpringState,
228 target: f32,
229 config: SpringConfig,
230 initial: f32,
231 playback: SpringPlayback,
232 updated_at: Instant,
233}
234
235impl<E: IntoElement + 'static> Element for SpringAnimationElement<E> {
236 type RequestLayoutState = AnyElement;
237 type PrepaintState = ();
238
239 fn id(&self) -> Option<ElementId> {
240 Some(self.id.clone())
241 }
242
243 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
244 None
245 }
246
247 fn request_layout(
248 &mut self,
249 global_id: Option<&GlobalElementId>,
250 _inspector_id: Option<&InspectorElementId>,
251 window: &mut Window,
252 cx: &mut App,
253 ) -> (crate::LayoutId, Self::RequestLayoutState) {
254 window.with_element_state(global_id.unwrap(), |state, window| {
255 let now = cx.background_executor().now();
256 let initial = self.initial.unwrap_or(self.target);
257 let mut state = state.unwrap_or_else(|| SpringElementState {
258 spring: SpringState {
259 position: initial,
260 velocity: 0.0,
261 },
262 target: self.target,
263 config: self.config,
264 initial,
265 playback: self.playback,
266 updated_at: now,
267 });
268
269 let elapsed = now.duration_since(state.updated_at).as_secs_f32();
270 match state.playback {
271 SpringPlayback::Running => {
272 state.spring = state.config.step(state.spring, state.target, elapsed);
273 }
274 SpringPlayback::Paused
275 | SpringPlayback::Stopped
276 | SpringPlayback::Completed
277 | SpringPlayback::Cancelled => {}
278 }
279
280 state.config = self.config;
281 state.target = self.target;
282
283 let done = match self.playback {
284 SpringPlayback::Running => {
285 if cx.reduce_motion() {
286 state.spring = SpringState {
287 position: state.target,
288 velocity: 0.0,
289 };
290 true
291 } else {
292 let done =
293 state
294 .config
295 .is_settled(state.spring, state.target, self.epsilon);
296 if done {
297 state.spring = SpringState {
298 position: state.target,
299 velocity: 0.0,
300 };
301 }
302 done
303 }
304 }
305 SpringPlayback::Paused => true,
306 SpringPlayback::Stopped => {
307 state.spring.velocity = 0.0;
308 true
309 }
310 SpringPlayback::Completed => {
311 state.spring = SpringState {
312 position: state.target,
313 velocity: 0.0,
314 };
315 true
316 }
317 SpringPlayback::Cancelled => {
318 state.spring = SpringState {
319 position: state.initial,
320 velocity: 0.0,
321 };
322 true
323 }
324 };
325 state.playback = self.playback;
326 state.updated_at = now;
327
328 let element = self.element.take().expect("should only be called once");
329 let animator = self.animator.take().expect("should only be called once");
330 let mut element = animator(element, state.spring.position).into_any_element();
331
332 if !done {
333 window.request_animation_frame();
334 }
335
336 ((element.request_layout(window, cx), element), state)
337 })
338 }
339
340 fn prepaint(
341 &mut self,
342 _id: Option<&GlobalElementId>,
343 _inspector_id: Option<&InspectorElementId>,
344 _bounds: crate::Bounds<crate::Pixels>,
345 element: &mut Self::RequestLayoutState,
346 window: &mut Window,
347 cx: &mut App,
348 ) -> Self::PrepaintState {
349 element.prepaint(window, cx);
350 }
351
352 fn paint(
353 &mut self,
354 _id: Option<&GlobalElementId>,
355 _inspector_id: Option<&InspectorElementId>,
356 _bounds: crate::Bounds<crate::Pixels>,
357 element: &mut Self::RequestLayoutState,
358 _: &mut Self::PrepaintState,
359 window: &mut Window,
360 cx: &mut App,
361 ) {
362 element.paint(window, cx);
363 }
364}
365
366impl<E: IntoElement + 'static> Element for AnimationElement<E> {
367 type RequestLayoutState = AnyElement;
368 type PrepaintState = ();
369
370 fn id(&self) -> Option<ElementId> {
371 Some(self.id.clone())
372 }
373
374 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
375 None
376 }
377
378 fn request_layout(
379 &mut self,
380 global_id: Option<&GlobalElementId>,
381 _inspector_id: Option<&InspectorElementId>,
382 window: &mut Window,
383 cx: &mut App,
384 ) -> (crate::LayoutId, Self::RequestLayoutState) {
385 window.with_element_state(global_id.unwrap(), |state, window| {
386 let mut state = state.unwrap_or_else(|| AnimationState {
387 start: cx.background_executor().now(),
388 animation_ix: 0,
389 delayed_frame_pending: Rc::new(Cell::new(false)),
390 });
391 let (animation_ix, delta, done) = if cx.reduce_motion() {
392 let animation_ix = self.animations.len() - 1;
393 let delta = if self.animations[animation_ix].oneshot {
394 1.0
395 } else {
396 0.0
397 };
398 (animation_ix, delta, true)
399 } else {
400 let animation_ix = state.animation_ix;
401 let duration = self.animations[animation_ix].duration;
402
403 let elapsed = if self.animations[animation_ix].synced && !duration.is_zero() {
404 let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
405 Duration::from_nanos((elapsed.as_nanos() % duration.as_nanos()) as u64)
407 } else {
408 cx.background_executor().now() - state.start
409 };
410 let mut delta = elapsed.as_secs_f32() / duration.as_secs_f32();
411
412 let mut done = false;
413 if delta > 1.0 {
414 if self.animations[animation_ix].oneshot {
415 if animation_ix >= self.animations.len() - 1 {
416 done = true;
417 } else {
418 state.start = cx.background_executor().now();
419 state.animation_ix += 1;
420 }
421 delta = 1.0;
422 } else {
423 delta %= 1.0;
424 }
425 }
426 (animation_ix, delta, done)
427 };
428 let delta = (self.animations[animation_ix].easing)(delta);
429
430 debug_assert!(delta.is_finite(), "animated value should be finite");
431
432 let element = self.element.take().expect("should only be called once");
433 let mut element = (self.animator)(element, animation_ix, delta).into_any_element();
434
435 if !done {
436 match self.animations[animation_ix].max_fps {
437 Some(max_fps) if max_fps.is_finite() && max_fps > 0.0 => {
438 if !state.delayed_frame_pending.get() {
439 state.delayed_frame_pending.set(true);
440 let delayed_frame_pending = state.delayed_frame_pending.clone();
441 let view = window.current_view();
442 let interval = Duration::from_secs_f32(1.0 / max_fps);
443 window
444 .spawn(cx, async move |cx| {
445 cx.background_executor().timer(interval).await;
446 delayed_frame_pending.set(false);
447 cx.update(move |_, cx| cx.notify(view)).ok();
448 })
449 .detach();
450 }
451 }
452 _ => window.request_animation_frame(),
453 }
454 }
455
456 ((element.request_layout(window, cx), element), state)
457 })
458 }
459
460 fn prepaint(
461 &mut self,
462 _id: Option<&GlobalElementId>,
463 _inspector_id: Option<&InspectorElementId>,
464 _bounds: crate::Bounds<crate::Pixels>,
465 element: &mut Self::RequestLayoutState,
466 window: &mut Window,
467 cx: &mut App,
468 ) -> Self::PrepaintState {
469 element.prepaint(window, cx);
470 }
471
472 fn paint(
473 &mut self,
474 _id: Option<&GlobalElementId>,
475 _inspector_id: Option<&InspectorElementId>,
476 _bounds: crate::Bounds<crate::Pixels>,
477 element: &mut Self::RequestLayoutState,
478 _: &mut Self::PrepaintState,
479 window: &mut Window,
480 cx: &mut App,
481 ) {
482 element.paint(window, cx);
483 }
484}
485
486mod easing {
487 use std::f32::consts::PI;
488
489 pub fn linear(delta: f32) -> f32 {
491 delta
492 }
493
494 pub fn quadratic(delta: f32) -> f32 {
496 delta * delta
497 }
498
499 pub fn ease_in_out(delta: f32) -> f32 {
501 if delta < 0.5 {
502 2.0 * delta * delta
503 } else {
504 let x = -2.0 * delta + 2.0;
505 1.0 - x * x / 2.0
506 }
507 }
508
509 pub fn ease_out_quint() -> impl Fn(f32) -> f32 {
511 move |delta| 1.0 - (1.0 - delta).powi(5)
512 }
513
514 pub fn heartbeat(delta: f32) -> f32 {
516 let beat = |center: f32, width: f32, height: f32| {
517 let x = (delta - center) / width;
518 height * (-x * x).exp()
519 };
520 beat(0.2, 0.06, 1.0) + beat(0.4, 0.05, 0.58)
521 }
522
523 pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
525 move |delta| {
526 if delta < 0.5 {
527 easing(delta * 2.0)
528 } else {
529 easing((1.0 - delta) * 2.0)
530 }
531 }
532 }
533
534 pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
536 let range = max - min;
537
538 move |delta| {
539 let t = (delta * 2.0 * PI).sin();
541 let breath = (t * t * t + t) / 2.0;
542
543 let normalized_alpha = (breath + 1.0) / 2.0;
545
546 min + (normalized_alpha * range)
547 }
548 }
549}
550
551#[cfg(test)]
552mod tests {
553 use std::{cell::RefCell, rc::Rc, time::Duration};
554
555 use crate::{
556 Animation, Context, InteractiveElement, Pixels, Render, SpringAnimation, SpringConfig,
557 TestAppContext, WindowHandle, div, prelude::*, px, size,
558 };
559
560 use super::*;
561
562 struct AnimationTestView {
563 rendered_deltas: Rc<RefCell<Vec<f32>>>,
564 max_fps: Option<f32>,
565 }
566
567 struct SyncedAnimationTestView {
568 show_second: bool,
569 first_deltas: Rc<RefCell<Vec<f32>>>,
570 second_deltas: Rc<RefCell<Vec<f32>>>,
571 }
572
573 struct SpringAnimationTestView {
574 target: Pixels,
575 initial: Option<Pixels>,
576 playback: SpringPlayback,
577 rendered_values: Rc<RefCell<Vec<Pixels>>>,
578 }
579
580 impl Render for SpringAnimationTestView {
581 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
582 let rendered_values = self.rendered_values.clone();
583 let mut animation = SpringAnimation::new(SpringConfig::new(100.0, 2.0, 1.0))
584 .to(self.target)
585 .with_epsilon(0.01)
586 .playback(self.playback);
587 if let Some(initial) = self.initial {
588 animation = animation.from(initial);
589 }
590 div().with_spring("spring-animation", animation, move |this, value| {
591 rendered_values.borrow_mut().push(value);
592 this.left(value)
593 })
594 }
595 }
596
597 impl Render for SyncedAnimationTestView {
598 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
599 let record_deltas = |deltas: Rc<RefCell<Vec<f32>>>| {
600 move |this, delta| {
601 deltas.borrow_mut().push(delta);
602 this
603 }
604 };
605 div()
606 .size_full()
607 .child(div().with_animation(
608 "first-synced-animation",
609 Animation::new(Duration::from_secs(1)).repeat_synced(),
610 record_deltas(self.first_deltas.clone()),
611 ))
612 .when(self.show_second, |this| {
613 this.child(div().with_animation(
614 "second-synced-animation",
615 Animation::new(Duration::from_secs(1)).repeat_synced(),
616 record_deltas(self.second_deltas.clone()),
617 ))
618 })
619 }
620 }
621
622 impl Render for AnimationTestView {
623 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
624 let rendered_deltas = self.rendered_deltas.clone();
625 let mut animation = Animation::new(Duration::from_secs(1));
628 if let Some(max_fps) = self.max_fps {
629 animation = animation.repeat_synced().with_max_fps(max_fps);
630 } else {
631 animation = animation.repeat();
632 }
633 div().size_full().child(div().with_animation(
634 "repeating-animation",
635 animation,
636 move |this, delta| {
637 rendered_deltas.borrow_mut().push(delta);
638 this
639 },
640 ))
641 }
642 }
643
644 fn open_test_window(
645 cx: &mut TestAppContext,
646 ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
647 open_test_window_with_max_fps(cx, None)
648 }
649
650 fn open_test_window_with_max_fps(
651 cx: &mut TestAppContext,
652 max_fps: Option<f32>,
653 ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
654 let rendered_deltas = Rc::new(RefCell::new(Vec::new()));
655 let window = cx.open_window(size(px(100.), px(100.)), {
656 let rendered_deltas = rendered_deltas.clone();
657 move |_, _| AnimationTestView {
658 rendered_deltas,
659 max_fps,
660 }
661 });
662 cx.run_until_parked();
663 (rendered_deltas, window)
664 }
665
666 fn simulate_next_frame<V: Render>(window: &WindowHandle<V>, cx: &mut TestAppContext) -> usize {
667 let callback_count = window
668 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
669 .unwrap();
670 cx.run_until_parked();
671 callback_count
672 }
673 #[test]
677 fn test_animation_parent() {
678 div()
679 .id("id")
680 .with_animation(
682 "animation",
683 Animation::new(Duration::from_secs(1)),
684 |el, _t| {
685 el
687 },
688 )
689 .child(
690 div(),
692 );
693 }
694
695 #[test]
696 fn test_spring_animation_parent() {
697 div()
698 .id("id")
699 .with_spring(
700 "spring-animation",
701 SpringAnimation::new(SpringConfig::new(100.0, 10.0, 1.0))
702 .to(px(10.0))
703 .from(px(0.0)),
704 |element, value| element.left(value),
705 )
706 .child(div());
707 }
708
709 #[gpui::test]
710 fn test_spring_animation_preserves_velocity_when_retargeted(cx: &mut TestAppContext) {
711 let rendered_values = Rc::new(RefCell::new(Vec::new()));
712 let window = cx.open_window(size(px(100.0), px(100.0)), {
713 let rendered_values = rendered_values.clone();
714 move |_, _| SpringAnimationTestView {
715 target: px(0.0),
716 initial: None,
717 playback: SpringPlayback::Running,
718 rendered_values,
719 }
720 });
721 cx.run_until_parked();
722 assert_eq!(*rendered_values.borrow(), vec![px(0.0)]);
723
724 window
725 .update(cx, |view, _, cx| {
726 view.target = px(100.0);
727 cx.notify();
728 })
729 .unwrap();
730 cx.run_until_parked();
731
732 cx.executor().advance_clock(Duration::from_millis(50));
733 assert!(simulate_next_frame(&window, cx) > 0);
734 let value_before_retargeting = *rendered_values.borrow().last().unwrap();
735 assert!(value_before_retargeting > px(0.0));
736 assert!(value_before_retargeting < px(100.0));
737
738 window
739 .update(cx, |view, _, cx| {
740 view.target = px(0.0);
741 cx.notify();
742 })
743 .unwrap();
744 cx.run_until_parked();
745
746 cx.executor().advance_clock(Duration::from_millis(5));
747 assert!(simulate_next_frame(&window, cx) > 0);
748 let value_after_retargeting = *rendered_values.borrow().last().unwrap();
749 assert!(value_after_retargeting > value_before_retargeting);
750 }
751
752 #[gpui::test]
753 fn test_paused_spring_resumes_with_its_velocity(cx: &mut TestAppContext) {
754 let rendered_values = Rc::new(RefCell::new(Vec::new()));
755 let window = cx.open_window(size(px(100.0), px(100.0)), {
756 let rendered_values = rendered_values.clone();
757 move |_, _| SpringAnimationTestView {
758 target: px(0.0),
759 initial: None,
760 playback: SpringPlayback::Running,
761 rendered_values,
762 }
763 });
764 cx.run_until_parked();
765
766 window
767 .update(cx, |view, _, cx| {
768 view.target = px(100.0);
769 cx.notify();
770 })
771 .unwrap();
772 cx.run_until_parked();
773 cx.executor().advance_clock(Duration::from_millis(50));
774 assert!(simulate_next_frame(&window, cx) > 0);
775
776 window
777 .update(cx, |view, _, cx| {
778 view.target = px(0.0);
779 view.playback = SpringPlayback::Paused;
780 cx.notify();
781 })
782 .unwrap();
783 cx.run_until_parked();
784 let paused_value = *rendered_values.borrow().last().unwrap();
785
786 cx.executor().advance_clock(Duration::from_millis(500));
787 assert!(simulate_next_frame(&window, cx) > 0);
788 assert_eq!(*rendered_values.borrow().last().unwrap(), paused_value);
789 assert_eq!(simulate_next_frame(&window, cx), 0);
790
791 window
792 .update(cx, |view, _, cx| {
793 view.playback = SpringPlayback::Running;
794 cx.notify();
795 })
796 .unwrap();
797 cx.run_until_parked();
798 cx.executor().advance_clock(Duration::from_millis(5));
799 assert!(simulate_next_frame(&window, cx) > 0);
800 assert!(*rendered_values.borrow().last().unwrap() > paused_value);
801 }
802
803 #[gpui::test]
804 fn test_stopped_spring_resumes_without_velocity(cx: &mut TestAppContext) {
805 let rendered_values = Rc::new(RefCell::new(Vec::new()));
806 let window = cx.open_window(size(px(100.0), px(100.0)), {
807 let rendered_values = rendered_values.clone();
808 move |_, _| SpringAnimationTestView {
809 target: px(0.0),
810 initial: None,
811 playback: SpringPlayback::Running,
812 rendered_values,
813 }
814 });
815 cx.run_until_parked();
816
817 window
818 .update(cx, |view, _, cx| {
819 view.target = px(1_000_000.0);
820 cx.notify();
821 })
822 .unwrap();
823 cx.run_until_parked();
824 cx.executor().advance_clock(Duration::from_millis(50));
825 assert!(simulate_next_frame(&window, cx) > 0);
826
827 window
828 .update(cx, |view, _, cx| {
829 view.target = px(0.0);
830 view.playback = SpringPlayback::Stopped;
831 cx.notify();
832 })
833 .unwrap();
834 cx.run_until_parked();
835 let stopped_value = *rendered_values.borrow().last().unwrap();
836
837 cx.executor().advance_clock(Duration::from_millis(500));
838 assert!(simulate_next_frame(&window, cx) > 0);
839 assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);
840 assert_eq!(simulate_next_frame(&window, cx), 0);
841
842 window
843 .update(cx, |view, _, cx| {
844 view.target = stopped_value;
845 view.playback = SpringPlayback::Running;
846 cx.notify();
847 })
848 .unwrap();
849 cx.run_until_parked();
850 assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);
851 assert_eq!(simulate_next_frame(&window, cx), 0);
852 }
853
854 #[gpui::test]
855 fn test_cancelled_and_completed_springs_resolve_their_endpoints(cx: &mut TestAppContext) {
856 let rendered_values = Rc::new(RefCell::new(Vec::new()));
857 let window = cx.open_window(size(px(100.0), px(100.0)), {
858 let rendered_values = rendered_values.clone();
859 move |_, _| SpringAnimationTestView {
860 target: px(100.0),
861 initial: Some(px(20.0)),
862 playback: SpringPlayback::Running,
863 rendered_values,
864 }
865 });
866 cx.run_until_parked();
867 assert_eq!(*rendered_values.borrow(), vec![px(20.0)]);
868
869 cx.executor().advance_clock(Duration::from_millis(50));
870 assert!(simulate_next_frame(&window, cx) > 0);
871 assert!(*rendered_values.borrow().last().unwrap() > px(20.0));
872
873 window
874 .update(cx, |view, _, cx| {
875 view.playback = SpringPlayback::Cancelled;
876 cx.notify();
877 })
878 .unwrap();
879 cx.run_until_parked();
880 assert_eq!(*rendered_values.borrow().last().unwrap(), px(20.0));
881 assert!(simulate_next_frame(&window, cx) > 0);
882 assert_eq!(simulate_next_frame(&window, cx), 0);
883
884 window
885 .update(cx, |view, _, cx| {
886 view.playback = SpringPlayback::Completed;
887 cx.notify();
888 })
889 .unwrap();
890 cx.run_until_parked();
891 assert_eq!(*rendered_values.borrow().last().unwrap(), px(100.0));
892 assert_eq!(simulate_next_frame(&window, cx), 0);
893 }
894
895 #[gpui::test]
896 fn test_spring_animation_respects_reduced_motion(cx: &mut TestAppContext) {
897 cx.update(|cx| cx.set_reduce_motion(true));
898 let rendered_values = Rc::new(RefCell::new(Vec::new()));
899 let window = cx.open_window(size(px(100.0), px(100.0)), {
900 let rendered_values = rendered_values.clone();
901 move |_, _| SpringAnimationTestView {
902 target: px(100.0),
903 initial: None,
904 playback: SpringPlayback::Running,
905 rendered_values,
906 }
907 });
908 cx.run_until_parked();
909
910 assert_eq!(*rendered_values.borrow(), vec![px(100.0)]);
911 assert_eq!(simulate_next_frame(&window, cx), 0);
912 }
913
914 #[gpui::test]
915 fn test_repeating_animation_schedules_animation_frames(cx: &mut TestAppContext) {
916 let (rendered_deltas, window) = open_test_window(cx);
917
918 assert_eq!(rendered_deltas.borrow().len(), 1);
919
920 for expected_frames in 2..=3 {
921 assert_eq!(simulate_next_frame(&window, cx), 1);
922 assert_eq!(rendered_deltas.borrow().len(), expected_frames);
923 }
924 }
925
926 #[gpui::test]
927 fn test_max_fps_schedules_timer_driven_frames(cx: &mut TestAppContext) {
928 let (rendered_deltas, window) = open_test_window_with_max_fps(cx, Some(10.0));
929
930 let assert_deltas_approx_eq = |expected: &[f32]| {
933 let actual = rendered_deltas.borrow();
934 assert_eq!(actual.len(), expected.len(), "deltas: {actual:?}");
935 for (actual, expected) in actual.iter().zip(expected) {
936 assert!(
937 (actual - expected).abs() < 1e-2,
938 "expected {expected}, got {actual}"
939 );
940 }
941 };
942
943 assert_deltas_approx_eq(&[0.0]);
944
945 assert_eq!(simulate_next_frame(&window, cx), 0);
947 assert_deltas_approx_eq(&[0.0]);
948
949 cx.executor().advance_clock(Duration::from_millis(105));
950 cx.run_until_parked();
951 assert_deltas_approx_eq(&[0.0, 0.105]);
952
953 cx.executor().advance_clock(Duration::from_millis(105));
954 cx.run_until_parked();
955 assert_deltas_approx_eq(&[0.0, 0.105, 0.21]);
956 }
957
958 #[gpui::test]
959 fn test_synced_animations_share_phase_across_elements(cx: &mut TestAppContext) {
960 let first_deltas = Rc::new(RefCell::new(Vec::new()));
961 let second_deltas = Rc::new(RefCell::new(Vec::new()));
962 let window = cx.open_window(size(px(100.), px(100.)), {
963 let first_deltas = first_deltas.clone();
964 let second_deltas = second_deltas.clone();
965 move |_, _| SyncedAnimationTestView {
966 show_second: false,
967 first_deltas,
968 second_deltas,
969 }
970 });
971 cx.run_until_parked();
972
973 assert_eq!(*first_deltas.borrow(), vec![0.0]);
974
975 cx.executor().advance_clock(Duration::from_millis(250));
976 simulate_next_frame(&window, cx);
977 assert_eq!(*first_deltas.borrow(), vec![0.0, 0.25]);
978
979 window
982 .update(cx, |view, _, cx| {
983 view.show_second = true;
984 cx.notify();
985 })
986 .unwrap();
987 cx.run_until_parked();
988 cx.executor().advance_clock(Duration::from_millis(250));
989 simulate_next_frame(&window, cx);
990
991 assert_eq!(*second_deltas.borrow().last().unwrap(), 0.5);
992 assert_eq!(
993 *first_deltas.borrow().last().unwrap(),
994 *second_deltas.borrow().last().unwrap()
995 );
996 assert!(second_deltas.borrow().iter().all(|delta| *delta > 0.0));
997
998 cx.executor().advance_clock(Duration::from_millis(2250));
1000 simulate_next_frame(&window, cx);
1001 assert_eq!(*first_deltas.borrow().last().unwrap(), 0.75);
1002
1003 cx.executor()
1006 .advance_clock(Duration::from_secs(300 * 24 * 60 * 60) + Duration::from_millis(500));
1007 simulate_next_frame(&window, cx);
1008 assert_eq!(*first_deltas.borrow().last().unwrap(), 0.25);
1009 }
1010
1011 #[gpui::test]
1012 fn test_reduce_motion_renders_single_static_frame(cx: &mut TestAppContext) {
1013 cx.update(|cx| cx.set_reduce_motion(true));
1014 let (rendered_deltas, window) = open_test_window(cx);
1015
1016 assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
1017
1018 assert_eq!(simulate_next_frame(&window, cx), 0);
1019 assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
1020 }
1021}