1use crate::scheduler::Instant;
4use std::{cell::Cell, rc::Rc, time::Duration};
5
6use crate::{
7 AnyElement, App, Element, ElementId, GlobalElementId, InspectorElementId, IntoElement,
8 ParentElement, Window,
9};
10
11pub use easing::*;
12use smallvec::SmallVec;
13
14#[inline]
19#[allow(clippy::panic)] fn invariant<T>(value: Option<T>, message: &str) -> T {
21 match value {
22 Some(value) => value,
23 None => panic!("{message}"),
24 }
25}
26
27#[derive(Clone)]
29pub struct Animation {
30 pub duration: Duration,
32 pub oneshot: bool,
34 pub synced: bool,
36 pub easing: Rc<dyn Fn(f32) -> f32>,
38 pub max_fps: Option<f32>,
41}
42
43impl Animation {
44 pub fn new(duration: Duration) -> Self {
47 Self {
48 duration,
49 oneshot: true,
50 synced: false,
51 easing: Rc::new(linear),
52 max_fps: None,
53 }
54 }
55
56 pub fn repeat(mut self) -> Self {
58 self.oneshot = false;
59 self
60 }
61
62 pub fn repeat_synced(mut self) -> Self {
64 self.oneshot = false;
65 self.synced = true;
66 self
67 }
68
69 pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
72 self.easing = Rc::new(easing);
73 self
74 }
75
76 pub fn with_max_fps(mut self, max_fps: f32) -> Self {
79 self.max_fps = Some(max_fps);
80 self
81 }
82}
83
84pub trait AnimationExt {
91 fn with_animation(
93 self,
94 id: impl Into<ElementId>,
95 animation: Animation,
96 animator: impl Fn(Self, f32) -> Self + 'static,
97 ) -> AnimationElement<Self>
98 where
99 Self: Sized,
100 {
101 AnimationElement {
102 id: id.into(),
103 element: Some(self),
104 animator: Box::new(move |this, _, value| animator(this, value)),
105 animations: smallvec::smallvec![animation],
106 }
107 }
108
109 fn with_animations(
111 self,
112 id: impl Into<ElementId>,
113 animations: Vec<Animation>,
114 animator: impl Fn(Self, usize, f32) -> Self + 'static,
115 ) -> AnimationElement<Self>
116 where
117 Self: Sized,
118 {
119 AnimationElement {
120 id: id.into(),
121 element: Some(self),
122 animator: Box::new(animator),
123 animations: animations.into(),
124 }
125 }
126}
127
128impl<E: IntoElement + 'static> AnimationExt for E {}
129
130pub struct AnimationElement<E> {
132 id: ElementId,
133 element: Option<E>,
134 animations: SmallVec<[Animation; 1]>,
135 animator: Box<dyn Fn(E, usize, f32) -> E + 'static>,
136}
137
138impl<E: ParentElement> ParentElement for AnimationElement<E> {
139 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
140 let Some(element) = &mut self.element else {
141 return;
142 };
143
144 element.extend(elements);
145 }
146}
147
148impl<E> AnimationElement<E> {
149 pub fn map_element(mut self, f: impl FnOnce(E) -> E) -> AnimationElement<E> {
151 self.element = self.element.map(f);
152 self
153 }
154}
155
156impl<E: IntoElement + 'static> IntoElement for AnimationElement<E> {
157 type Element = AnimationElement<E>;
158
159 fn into_element(self) -> Self::Element {
160 self
161 }
162}
163
164struct AnimationState {
165 start: Instant,
166 animation_ix: usize,
167 delayed_frame_pending: Rc<Cell<bool>>,
170}
171
172impl<E: IntoElement + 'static> Element for AnimationElement<E> {
173 type RequestLayoutState = AnyElement;
174 type PrepaintState = ();
175
176 fn id(&self) -> Option<ElementId> {
177 Some(self.id.clone())
178 }
179
180 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
181 None
182 }
183
184 fn request_layout(
185 &mut self,
186 global_id: Option<&GlobalElementId>,
187 _inspector_id: Option<&InspectorElementId>,
188 window: &mut Window,
189 cx: &mut App,
190 ) -> (crate::LayoutId, Self::RequestLayoutState) {
191 window.with_element_state(
193 invariant(global_id, "动画元素:元素必有 id"),
194 |state, window| {
195 let mut state = state.unwrap_or_else(|| AnimationState {
196 start: cx.background_executor().now(),
197 animation_ix: 0,
198 delayed_frame_pending: Rc::new(Cell::new(false)),
199 });
200 let (animation_ix, delta, done) = if cx.reduce_motion() {
201 let animation_ix = self.animations.len() - 1;
202 let delta = if self.animations[animation_ix].oneshot {
203 1.0
204 } else {
205 0.0
206 };
207 (animation_ix, delta, true)
208 } else {
209 let animation_ix = state.animation_ix;
210 let duration = self.animations[animation_ix].duration;
211
212 let elapsed = if self.animations[animation_ix].synced && !duration.is_zero() {
213 let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
214 Duration::from_nanos((elapsed.as_nanos() % duration.as_nanos()) as u64)
216 } else {
217 cx.background_executor().now() - state.start
218 };
219 let mut delta = elapsed.as_secs_f32() / duration.as_secs_f32();
220
221 let mut done = false;
222 if delta > 1.0 {
223 if self.animations[animation_ix].oneshot {
224 if animation_ix >= self.animations.len() - 1 {
225 done = true;
226 } else {
227 state.start = cx.background_executor().now();
228 state.animation_ix += 1;
229 }
230 delta = 1.0;
231 } else {
232 delta %= 1.0;
233 }
234 }
235 (animation_ix, delta, done)
236 };
237 let delta = (self.animations[animation_ix].easing)(delta);
238
239 debug_assert!(
240 (0.0..=1.0).contains(&delta),
241 "delta should always be between 0 and 1"
242 );
243
244 let element = invariant(self.element.take(), "动画元素:element 每帧只取一次");
246 let mut element = (self.animator)(element, animation_ix, delta).into_any_element();
247
248 if !done {
249 match self.animations[animation_ix].max_fps {
250 Some(max_fps) if max_fps.is_finite() && max_fps > 0.0 => {
251 if !state.delayed_frame_pending.get() {
252 state.delayed_frame_pending.set(true);
253 let delayed_frame_pending = state.delayed_frame_pending.clone();
254 let view = window.current_view();
255 let interval = Duration::from_secs_f32(1.0 / max_fps);
256 window
257 .spawn(cx, async move |cx| {
258 cx.background_executor().timer(interval).await;
259 delayed_frame_pending.set(false);
260 cx.update(move |_, cx| cx.notify(view)).ok();
261 })
262 .detach();
263 }
264 }
265 _ => window.request_animation_frame(),
266 }
267 }
268
269 ((element.request_layout(window, cx), element), state)
270 },
271 )
272 }
273
274 fn prepaint(
275 &mut self,
276 _id: Option<&GlobalElementId>,
277 _inspector_id: Option<&InspectorElementId>,
278 _bounds: crate::Bounds<crate::Pixels>,
279 element: &mut Self::RequestLayoutState,
280 window: &mut Window,
281 cx: &mut App,
282 ) -> Self::PrepaintState {
283 element.prepaint(window, cx);
284 }
285
286 fn paint(
287 &mut self,
288 _id: Option<&GlobalElementId>,
289 _inspector_id: Option<&InspectorElementId>,
290 _bounds: crate::Bounds<crate::Pixels>,
291 element: &mut Self::RequestLayoutState,
292 _: &mut Self::PrepaintState,
293 window: &mut Window,
294 cx: &mut App,
295 ) {
296 element.paint(window, cx);
297 }
298}
299
300mod easing {
301 use std::f32::consts::PI;
302
303 pub fn linear(delta: f32) -> f32 {
305 delta
306 }
307
308 pub fn quadratic(delta: f32) -> f32 {
310 delta * delta
311 }
312
313 pub fn ease_in_out(delta: f32) -> f32 {
315 if delta < 0.5 {
316 2.0 * delta * delta
317 } else {
318 let x = -2.0 * delta + 2.0;
319 1.0 - x * x / 2.0
320 }
321 }
322
323 pub fn ease_out_quint() -> impl Fn(f32) -> f32 {
325 move |delta| 1.0 - (1.0 - delta).powi(5)
326 }
327
328 pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
330 move |delta| {
331 if delta < 0.5 {
332 easing(delta * 2.0)
333 } else {
334 easing((1.0 - delta) * 2.0)
335 }
336 }
337 }
338
339 pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
341 let range = max - min;
342
343 move |delta| {
344 let t = (delta * 2.0 * PI).sin();
346 let breath = (t * t * t + t) / 2.0;
347
348 let normalized_alpha = (breath + 1.0) / 2.0;
350
351 min + (normalized_alpha * range)
352 }
353 }
354}
355
356#[cfg(test)]
357mod tests {
358 use std::{cell::RefCell, rc::Rc, time::Duration};
359
360 use crate::{
361 Animation, Context, InteractiveElement, Render, TestAppContext, WindowHandle, div,
362 prelude::*, px, size,
363 };
364
365 use super::*;
366
367 struct AnimationTestView {
368 rendered_deltas: Rc<RefCell<Vec<f32>>>,
369 max_fps: Option<f32>,
370 }
371
372 struct SyncedAnimationTestView {
373 show_second: bool,
374 first_deltas: Rc<RefCell<Vec<f32>>>,
375 second_deltas: Rc<RefCell<Vec<f32>>>,
376 }
377
378 impl Render for SyncedAnimationTestView {
379 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
380 let record_deltas = |deltas: Rc<RefCell<Vec<f32>>>| {
381 move |this, delta| {
382 deltas.borrow_mut().push(delta);
383 this
384 }
385 };
386 div()
387 .size_full()
388 .child(div().with_animation(
389 "first-synced-animation",
390 Animation::new(Duration::from_secs(1)).repeat_synced(),
391 record_deltas(self.first_deltas.clone()),
392 ))
393 .when(self.show_second, |this| {
394 this.child(div().with_animation(
395 "second-synced-animation",
396 Animation::new(Duration::from_secs(1)).repeat_synced(),
397 record_deltas(self.second_deltas.clone()),
398 ))
399 })
400 }
401 }
402
403 impl Render for AnimationTestView {
404 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
405 let rendered_deltas = self.rendered_deltas.clone();
406 let mut animation = Animation::new(Duration::from_secs(1));
409 if let Some(max_fps) = self.max_fps {
410 animation = animation.repeat_synced().with_max_fps(max_fps);
411 } else {
412 animation = animation.repeat();
413 }
414 div().size_full().child(div().with_animation(
415 "repeating-animation",
416 animation,
417 move |this, delta| {
418 rendered_deltas.borrow_mut().push(delta);
419 this
420 },
421 ))
422 }
423 }
424
425 fn open_test_window(
426 cx: &mut TestAppContext,
427 ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
428 open_test_window_with_max_fps(cx, None)
429 }
430
431 fn open_test_window_with_max_fps(
432 cx: &mut TestAppContext,
433 max_fps: Option<f32>,
434 ) -> (Rc<RefCell<Vec<f32>>>, WindowHandle<AnimationTestView>) {
435 let rendered_deltas = Rc::new(RefCell::new(Vec::new()));
436 let window = cx.open_window(size(px(100.), px(100.)), {
437 let rendered_deltas = rendered_deltas.clone();
438 move |_, _| AnimationTestView {
439 rendered_deltas,
440 max_fps,
441 }
442 });
443 cx.run_until_parked();
444 (rendered_deltas, window)
445 }
446
447 fn simulate_next_frame<V: Render>(window: &WindowHandle<V>, cx: &mut TestAppContext) -> usize {
448 let callback_count = window
449 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
450 .unwrap();
451 cx.run_until_parked();
452 callback_count
453 }
454 #[test]
458 fn test_animation_parent() {
459 div()
460 .id("id")
461 .with_animation(
463 "animation",
464 Animation::new(Duration::from_secs(1)),
465 |el, _t| {
466 el
468 },
469 )
470 .child(
471 div(),
473 );
474 }
475
476 #[rgpui::test]
477 fn test_repeating_animation_schedules_animation_frames(cx: &mut TestAppContext) {
478 let (rendered_deltas, window) = open_test_window(cx);
479
480 assert_eq!(rendered_deltas.borrow().len(), 1);
481
482 for expected_frames in 2..=3 {
483 assert_eq!(simulate_next_frame(&window, cx), 1);
484 assert_eq!(rendered_deltas.borrow().len(), expected_frames);
485 }
486 }
487
488 #[rgpui::test]
489 fn test_max_fps_schedules_timer_driven_frames(cx: &mut TestAppContext) {
490 let (rendered_deltas, window) = open_test_window_with_max_fps(cx, Some(10.0));
491
492 let assert_deltas_approx_eq = |expected: &[f32]| {
495 let actual = rendered_deltas.borrow();
496 assert_eq!(actual.len(), expected.len(), "deltas: {actual:?}");
497 for (actual, expected) in actual.iter().zip(expected) {
498 assert!(
499 (actual - expected).abs() < 1e-2,
500 "expected {expected}, got {actual}"
501 );
502 }
503 };
504
505 assert_deltas_approx_eq(&[0.0]);
506
507 assert_eq!(simulate_next_frame(&window, cx), 0);
509 assert_deltas_approx_eq(&[0.0]);
510
511 cx.executor().advance_clock(Duration::from_millis(105));
512 cx.run_until_parked();
513 assert_deltas_approx_eq(&[0.0, 0.105]);
514
515 cx.executor().advance_clock(Duration::from_millis(105));
516 cx.run_until_parked();
517 assert_deltas_approx_eq(&[0.0, 0.105, 0.21]);
518 }
519
520 #[rgpui::test]
521 fn test_synced_animations_share_phase_across_elements(cx: &mut TestAppContext) {
522 let first_deltas = Rc::new(RefCell::new(Vec::new()));
523 let second_deltas = Rc::new(RefCell::new(Vec::new()));
524 let window = cx.open_window(size(px(100.), px(100.)), {
525 let first_deltas = first_deltas.clone();
526 let second_deltas = second_deltas.clone();
527 move |_, _| SyncedAnimationTestView {
528 show_second: false,
529 first_deltas,
530 second_deltas,
531 }
532 });
533 cx.run_until_parked();
534
535 assert_eq!(*first_deltas.borrow(), vec![0.0]);
536
537 cx.executor().advance_clock(Duration::from_millis(250));
538 simulate_next_frame(&window, cx);
539 assert_eq!(*first_deltas.borrow(), vec![0.0, 0.25]);
540
541 window
544 .update(cx, |view, _, cx| {
545 view.show_second = true;
546 cx.notify();
547 })
548 .unwrap();
549 cx.run_until_parked();
550 cx.executor().advance_clock(Duration::from_millis(250));
551 simulate_next_frame(&window, cx);
552
553 assert_eq!(*second_deltas.borrow().last().unwrap(), 0.5);
554 assert_eq!(
555 *first_deltas.borrow().last().unwrap(),
556 *second_deltas.borrow().last().unwrap()
557 );
558 assert!(second_deltas.borrow().iter().all(|delta| *delta > 0.0));
559
560 cx.executor().advance_clock(Duration::from_millis(2250));
562 simulate_next_frame(&window, cx);
563 assert_eq!(*first_deltas.borrow().last().unwrap(), 0.75);
564
565 cx.executor()
568 .advance_clock(Duration::from_secs(300 * 24 * 60 * 60) + Duration::from_millis(500));
569 simulate_next_frame(&window, cx);
570 assert_eq!(*first_deltas.borrow().last().unwrap(), 0.25);
571 }
572
573 #[rgpui::test]
574 fn test_reduce_motion_renders_single_static_frame(cx: &mut TestAppContext) {
575 cx.update(|cx| cx.set_reduce_motion(true));
576 let (rendered_deltas, window) = open_test_window(cx);
577
578 assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
579
580 assert_eq!(simulate_next_frame(&window, cx), 0);
581 assert_eq!(*rendered_deltas.borrow(), vec![0.0]);
582 }
583}