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 bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
516 move |delta| {
517 if delta < 0.5 {
518 easing(delta * 2.0)
519 } else {
520 easing((1.0 - delta) * 2.0)
521 }
522 }
523 }
524
525 pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
527 let range = max - min;
528
529 move |delta| {
530 let t = (delta * 2.0 * PI).sin();
532 let breath = (t * t * t + t) / 2.0;
533
534 let normalized_alpha = (breath + 1.0) / 2.0;
536
537 min + (normalized_alpha * range)
538 }
539 }
540}
541
542#[cfg(test)]
543mod tests {
544 use std::{cell::RefCell, rc::Rc, time::Duration};
545
546 use crate::{
547 Animation, Context, InteractiveElement, Pixels, Render, SpringAnimation, SpringConfig,
548 TestAppContext, WindowHandle, div, prelude::*, px, size,
549 };
550
551 use super::*;
552
553 struct AnimationTestView {
554 rendered_deltas: Rc<RefCell<Vec<f32>>>,
555 max_fps: Option<f32>,
556 }
557
558 struct SyncedAnimationTestView {
559 show_second: bool,
560 first_deltas: Rc<RefCell<Vec<f32>>>,
561 second_deltas: Rc<RefCell<Vec<f32>>>,
562 }
563
564 struct SpringAnimationTestView {
565 target: Pixels,
566 initial: Option<Pixels>,
567 playback: SpringPlayback,
568 rendered_values: Rc<RefCell<Vec<Pixels>>>,
569 }
570
571 impl Render for SpringAnimationTestView {
572 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
573 let rendered_values = self.rendered_values.clone();
574 let mut animation = SpringAnimation::new(SpringConfig::new(100.0, 2.0, 1.0))
575 .to(self.target)
576 .with_epsilon(0.01)
577 .playback(self.playback);
578 if let Some(initial) = self.initial {
579 animation = animation.from(initial);
580 }
581 div().with_spring("spring-animation", animation, move |this, value| {
582 rendered_values.borrow_mut().push(value);
583 this.left(value)
584 })
585 }
586 }
587
588 impl Render for SyncedAnimationTestView {
589 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
590 let record_deltas = |deltas: Rc<RefCell<Vec<f32>>>| {
591 move |this, delta| {
592 deltas.borrow_mut().push(delta);
593 this
594 }
595 };
596 div()
597 .size_full()
598 .child(div().with_animation(
599 "first-synced-animation",
600 Animation::new(Duration::from_secs(1)).repeat_synced(),
601 record_deltas(self.first_deltas.clone()),
602 ))
603 .when(self.show_second, |this| {
604 this.child(div().with_animation(
605 "second-synced-animation",
606 Animation::new(Duration::from_secs(1)).repeat_synced(),
607 record_deltas(self.second_deltas.clone()),
608 ))
609 })
610 }
611 }
612
613 impl Render for AnimationTestView {
614 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
615 let rendered_deltas = self.rendered_deltas.clone();
616 let mut animation = Animation::new(Duration::from_secs(1));
619 if let Some(max_fps) = self.max_fps {
620 animation = animation.repeat_synced().with_max_fps(max_fps);
621 } else {
622 animation = animation.repeat();
623 }
624 div().size_full().child(div().with_animation(
625 "repeating-animation",
626 animation,
627 move |this, delta| {
628 rendered_deltas.borrow_mut().push(delta);
629 this
630 },
631 ))
632 }
633 }
634
635 fn open_test_window(
636 cx: &mut TestAppContext,
637 ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
638 open_test_window_with_max_fps(cx, None)
639 }
640
641 fn open_test_window_with_max_fps(
642 cx: &mut TestAppContext,
643 max_fps: Option<f32>,
644 ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
645 let rendered_deltas = Rc::new(RefCell::new(Vec::new()));
646 let window = cx.open_window(size(px(100.), px(100.)), {
647 let rendered_deltas = rendered_deltas.clone();
648 move |_, _| AnimationTestView {
649 rendered_deltas,
650 max_fps,
651 }
652 });
653 cx.run_until_parked();
654 (rendered_deltas, window)
655 }
656
657 fn simulate_next_frame<V: Render>(window: &WindowHandle<V>, cx: &mut TestAppContext) -> usize {
658 let callback_count = window
659 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
660 .unwrap();
661 cx.run_until_parked();
662 callback_count
663 }
664 #[test]
668 fn test_animation_parent() {
669 div()
670 .id("id")
671 .with_animation(
673 "animation",
674 Animation::new(Duration::from_secs(1)),
675 |el, _t| {
676 el
678 },
679 )
680 .child(
681 div(),
683 );
684 }
685
686 #[test]
687 fn test_spring_animation_parent() {
688 div()
689 .id("id")
690 .with_spring(
691 "spring-animation",
692 SpringAnimation::new(SpringConfig::new(100.0, 10.0, 1.0))
693 .to(px(10.0))
694 .from(px(0.0)),
695 |element, value| element.left(value),
696 )
697 .child(div());
698 }
699
700 #[gpui::test]
701 fn test_spring_animation_preserves_velocity_when_retargeted(cx: &mut TestAppContext) {
702 let rendered_values = Rc::new(RefCell::new(Vec::new()));
703 let window = cx.open_window(size(px(100.0), px(100.0)), {
704 let rendered_values = rendered_values.clone();
705 move |_, _| SpringAnimationTestView {
706 target: px(0.0),
707 initial: None,
708 playback: SpringPlayback::Running,
709 rendered_values,
710 }
711 });
712 cx.run_until_parked();
713 assert_eq!(*rendered_values.borrow(), vec![px(0.0)]);
714
715 window
716 .update(cx, |view, _, cx| {
717 view.target = px(100.0);
718 cx.notify();
719 })
720 .unwrap();
721 cx.run_until_parked();
722
723 cx.executor().advance_clock(Duration::from_millis(50));
724 assert!(simulate_next_frame(&window, cx) > 0);
725 let value_before_retargeting = *rendered_values.borrow().last().unwrap();
726 assert!(value_before_retargeting > px(0.0));
727 assert!(value_before_retargeting < px(100.0));
728
729 window
730 .update(cx, |view, _, cx| {
731 view.target = px(0.0);
732 cx.notify();
733 })
734 .unwrap();
735 cx.run_until_parked();
736
737 cx.executor().advance_clock(Duration::from_millis(5));
738 assert!(simulate_next_frame(&window, cx) > 0);
739 let value_after_retargeting = *rendered_values.borrow().last().unwrap();
740 assert!(value_after_retargeting > value_before_retargeting);
741 }
742
743 #[gpui::test]
744 fn test_paused_spring_resumes_with_its_velocity(cx: &mut TestAppContext) {
745 let rendered_values = Rc::new(RefCell::new(Vec::new()));
746 let window = cx.open_window(size(px(100.0), px(100.0)), {
747 let rendered_values = rendered_values.clone();
748 move |_, _| SpringAnimationTestView {
749 target: px(0.0),
750 initial: None,
751 playback: SpringPlayback::Running,
752 rendered_values,
753 }
754 });
755 cx.run_until_parked();
756
757 window
758 .update(cx, |view, _, cx| {
759 view.target = px(100.0);
760 cx.notify();
761 })
762 .unwrap();
763 cx.run_until_parked();
764 cx.executor().advance_clock(Duration::from_millis(50));
765 assert!(simulate_next_frame(&window, cx) > 0);
766
767 window
768 .update(cx, |view, _, cx| {
769 view.target = px(0.0);
770 view.playback = SpringPlayback::Paused;
771 cx.notify();
772 })
773 .unwrap();
774 cx.run_until_parked();
775 let paused_value = *rendered_values.borrow().last().unwrap();
776
777 cx.executor().advance_clock(Duration::from_millis(500));
778 assert!(simulate_next_frame(&window, cx) > 0);
779 assert_eq!(*rendered_values.borrow().last().unwrap(), paused_value);
780 assert_eq!(simulate_next_frame(&window, cx), 0);
781
782 window
783 .update(cx, |view, _, cx| {
784 view.playback = SpringPlayback::Running;
785 cx.notify();
786 })
787 .unwrap();
788 cx.run_until_parked();
789 cx.executor().advance_clock(Duration::from_millis(5));
790 assert!(simulate_next_frame(&window, cx) > 0);
791 assert!(*rendered_values.borrow().last().unwrap() > paused_value);
792 }
793
794 #[gpui::test]
795 fn test_stopped_spring_resumes_without_velocity(cx: &mut TestAppContext) {
796 let rendered_values = Rc::new(RefCell::new(Vec::new()));
797 let window = cx.open_window(size(px(100.0), px(100.0)), {
798 let rendered_values = rendered_values.clone();
799 move |_, _| SpringAnimationTestView {
800 target: px(0.0),
801 initial: None,
802 playback: SpringPlayback::Running,
803 rendered_values,
804 }
805 });
806 cx.run_until_parked();
807
808 window
809 .update(cx, |view, _, cx| {
810 view.target = px(1_000_000.0);
811 cx.notify();
812 })
813 .unwrap();
814 cx.run_until_parked();
815 cx.executor().advance_clock(Duration::from_millis(50));
816 assert!(simulate_next_frame(&window, cx) > 0);
817
818 window
819 .update(cx, |view, _, cx| {
820 view.target = px(0.0);
821 view.playback = SpringPlayback::Stopped;
822 cx.notify();
823 })
824 .unwrap();
825 cx.run_until_parked();
826 let stopped_value = *rendered_values.borrow().last().unwrap();
827
828 cx.executor().advance_clock(Duration::from_millis(500));
829 assert!(simulate_next_frame(&window, cx) > 0);
830 assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);
831 assert_eq!(simulate_next_frame(&window, cx), 0);
832
833 window
834 .update(cx, |view, _, cx| {
835 view.target = stopped_value;
836 view.playback = SpringPlayback::Running;
837 cx.notify();
838 })
839 .unwrap();
840 cx.run_until_parked();
841 assert_eq!(*rendered_values.borrow().last().unwrap(), stopped_value);
842 assert_eq!(simulate_next_frame(&window, cx), 0);
843 }
844
845 #[gpui::test]
846 fn test_cancelled_and_completed_springs_resolve_their_endpoints(cx: &mut TestAppContext) {
847 let rendered_values = Rc::new(RefCell::new(Vec::new()));
848 let window = cx.open_window(size(px(100.0), px(100.0)), {
849 let rendered_values = rendered_values.clone();
850 move |_, _| SpringAnimationTestView {
851 target: px(100.0),
852 initial: Some(px(20.0)),
853 playback: SpringPlayback::Running,
854 rendered_values,
855 }
856 });
857 cx.run_until_parked();
858 assert_eq!(*rendered_values.borrow(), vec![px(20.0)]);
859
860 cx.executor().advance_clock(Duration::from_millis(50));
861 assert!(simulate_next_frame(&window, cx) > 0);
862 assert!(*rendered_values.borrow().last().unwrap() > px(20.0));
863
864 window
865 .update(cx, |view, _, cx| {
866 view.playback = SpringPlayback::Cancelled;
867 cx.notify();
868 })
869 .unwrap();
870 cx.run_until_parked();
871 assert_eq!(*rendered_values.borrow().last().unwrap(), px(20.0));
872 assert!(simulate_next_frame(&window, cx) > 0);
873 assert_eq!(simulate_next_frame(&window, cx), 0);
874
875 window
876 .update(cx, |view, _, cx| {
877 view.playback = SpringPlayback::Completed;
878 cx.notify();
879 })
880 .unwrap();
881 cx.run_until_parked();
882 assert_eq!(*rendered_values.borrow().last().unwrap(), px(100.0));
883 assert_eq!(simulate_next_frame(&window, cx), 0);
884 }
885
886 #[gpui::test]
887 fn test_spring_animation_respects_reduced_motion(cx: &mut TestAppContext) {
888 cx.update(|cx| cx.set_reduce_motion(true));
889 let rendered_values = Rc::new(RefCell::new(Vec::new()));
890 let window = cx.open_window(size(px(100.0), px(100.0)), {
891 let rendered_values = rendered_values.clone();
892 move |_, _| SpringAnimationTestView {
893 target: px(100.0),
894 initial: None,
895 playback: SpringPlayback::Running,
896 rendered_values,
897 }
898 });
899 cx.run_until_parked();
900
901 assert_eq!(*rendered_values.borrow(), vec![px(100.0)]);
902 assert_eq!(simulate_next_frame(&window, cx), 0);
903 }
904
905 #[gpui::test]
906 fn test_repeating_animation_schedules_animation_frames(cx: &mut TestAppContext) {
907 let (rendered_deltas, window) = open_test_window(cx);
908
909 assert_eq!(rendered_deltas.borrow().len(), 1);
910
911 for expected_frames in 2..=3 {
912 assert_eq!(simulate_next_frame(&window, cx), 1);
913 assert_eq!(rendered_deltas.borrow().len(), expected_frames);
914 }
915 }
916
917 #[gpui::test]
918 fn test_max_fps_schedules_timer_driven_frames(cx: &mut TestAppContext) {
919 let (rendered_deltas, window) = open_test_window_with_max_fps(cx, Some(10.0));
920
921 let assert_deltas_approx_eq = |expected: &[f32]| {
924 let actual = rendered_deltas.borrow();
925 assert_eq!(actual.len(), expected.len(), "deltas: {actual:?}");
926 for (actual, expected) in actual.iter().zip(expected) {
927 assert!(
928 (actual - expected).abs() < 1e-2,
929 "expected {expected}, got {actual}"
930 );
931 }
932 };
933
934 assert_deltas_approx_eq(&[0.0]);
935
936 assert_eq!(simulate_next_frame(&window, cx), 0);
938 assert_deltas_approx_eq(&[0.0]);
939
940 cx.executor().advance_clock(Duration::from_millis(105));
941 cx.run_until_parked();
942 assert_deltas_approx_eq(&[0.0, 0.105]);
943
944 cx.executor().advance_clock(Duration::from_millis(105));
945 cx.run_until_parked();
946 assert_deltas_approx_eq(&[0.0, 0.105, 0.21]);
947 }
948
949 #[gpui::test]
950 fn test_synced_animations_share_phase_across_elements(cx: &mut TestAppContext) {
951 let first_deltas = Rc::new(RefCell::new(Vec::new()));
952 let second_deltas = Rc::new(RefCell::new(Vec::new()));
953 let window = cx.open_window(size(px(100.), px(100.)), {
954 let first_deltas = first_deltas.clone();
955 let second_deltas = second_deltas.clone();
956 move |_, _| SyncedAnimationTestView {
957 show_second: false,
958 first_deltas,
959 second_deltas,
960 }
961 });
962 cx.run_until_parked();
963
964 assert_eq!(*first_deltas.borrow(), vec![0.0]);
965
966 cx.executor().advance_clock(Duration::from_millis(250));
967 simulate_next_frame(&window, cx);
968 assert_eq!(*first_deltas.borrow(), vec![0.0, 0.25]);
969
970 window
973 .update(cx, |view, _, cx| {
974 view.show_second = true;
975 cx.notify();
976 })
977 .unwrap();
978 cx.run_until_parked();
979 cx.executor().advance_clock(Duration::from_millis(250));
980 simulate_next_frame(&window, cx);
981
982 assert_eq!(*second_deltas.borrow().last().unwrap(), 0.5);
983 assert_eq!(
984 *first_deltas.borrow().last().unwrap(),
985 *second_deltas.borrow().last().unwrap()
986 );
987 assert!(second_deltas.borrow().iter().all(|delta| *delta > 0.0));
988
989 cx.executor().advance_clock(Duration::from_millis(2250));
991 simulate_next_frame(&window, cx);
992 assert_eq!(*first_deltas.borrow().last().unwrap(), 0.75);
993
994 cx.executor()
997 .advance_clock(Duration::from_secs(300 * 24 * 60 * 60) + Duration::from_millis(500));
998 simulate_next_frame(&window, cx);
999 assert_eq!(*first_deltas.borrow().last().unwrap(), 0.25);
1000 }
1001
1002 #[gpui::test]
1003 fn test_reduce_motion_renders_single_static_frame(cx: &mut TestAppContext) {
1004 cx.update(|cx| cx.set_reduce_motion(true));
1005 let (rendered_deltas, window) = open_test_window(cx);
1006
1007 assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
1008
1009 assert_eq!(simulate_next_frame(&window, cx), 0);
1010 assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
1011 }
1012}