Skip to main content

rgpui/elements/
animation.rs

1//! 动画元素,提供基础动画框架,支持弹性动画、时间驱动和帧回调。
2
3use 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/// 内部不变量:值为 `None` 说明前提被破坏(元素 id 缺失、回调被重复取用等),必须立刻暴露。
15///
16/// 统一走这里而不是散落的 `unwrap`:语义与原先一致(同样 panic),但把「这是不变量
17/// 断言」的意图写进调用点,模块级 `deny` 仍能拦住随手写的 unwrap。
18#[inline]
19#[allow(clippy::panic)] // 不变量断言:前提被破坏必须立刻暴露
20fn invariant<T>(value: Option<T>, message: &str) -> T {
21    match value {
22        Some(value) => value,
23        None => panic!("{message}"),
24    }
25}
26
27/// 一个可以应用于元素的动画。
28#[derive(Clone)]
29pub struct Animation {
30    /// 动画持续时间
31    pub duration: Duration,
32    /// 动画结束后是否循环
33    pub oneshot: bool,
34    /// 是否从共享时钟派生相位。参见 [`Animation::repeat_synced`]。
35    pub synced: bool,
36    /// 接受 0 到 1 之间的 delta 值,根据给定的缓动函数返回新的 delta 值。
37    pub easing: Rc<dyn Fn(f32) -> f32>,
38    /// 该动画每秒最多重新渲染的次数。
39    /// 当为 `None` 时,动画会在每一帧重新渲染。
40    pub max_fps: Option<f32>,
41}
42
43impl Animation {
44    /// 创建一个具有指定持续时间的新动画。
45    /// 默认情况下动画仅播放一次,并使用线性缓动函数。
46    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    /// 设置动画结束后循环播放。
57    pub fn repeat(mut self) -> Self {
58        self.oneshot = false;
59        self
60    }
61
62    /// 设置动画结束后循环播放,并与整个 [`App`] 共享的时钟相位锁定。
63    pub fn repeat_synced(mut self) -> Self {
64        self.oneshot = false;
65        self.synced = true;
66        self
67    }
68
69    /// 设置此动画使用的缓动函数。
70    /// 缓动函数接受 0 到 1 之间的时间 delta 值,返回新的 delta 值。
71    pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
72        self.easing = Rc::new(easing);
73        self
74    }
75
76    /// 限制该动画的渲染频率。不再每帧重渲染,而是安排在当前帧之后
77    /// `1 / max_fps` 秒再渲染。非有限或非正数的值会被忽略。
78    pub fn with_max_fps(mut self, max_fps: f32) -> Self {
79        self.max_fps = Some(max_fps);
80        self
81    }
82}
83
84/// 一个扩展 trait,用于为元素和组件添加动画包装器。
85///
86/// 通过此 trait 渲染的动画会自动遵守
87/// [`App::reduce_motion`](crate::App::reduce_motion):启用时,
88/// 元素将以静态状态渲染(单次动画显示结束状态,循环动画显示起始状态),
89/// 且不会调度动画帧。
90pub trait AnimationExt {
91    /// 使用动画渲染此组件或元素
92    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    /// 使用动画链渲染此组件或元素
110    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
130/// 一个将动画应用于另一个元素的 RGPUI 元素
131pub 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    /// 对被动画的元素应用给定函数后,返回新的 [`AnimationElement<E>`]。
150    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    /// 是否已安排了节流后的重渲染(参见 [`Animation::with_max_fps`]),
168    /// 以避免重叠渲染叠加多余的定时器。
169    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        // id() 恒返回 Some,框架必带元素 id
192        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                        // Reduce modulo the duration before f32 conversion, which loses sub-second precision at scale.
215                        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                // element 构造时必带,且每帧只取一次
245                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    /// 线性缓动函数,即 delta 本身
304    pub fn linear(delta: f32) -> f32 {
305        delta
306    }
307
308    /// 二次缓动函数,delta * delta
309    pub fn quadratic(delta: f32) -> f32 {
310        delta * delta
311    }
312
313    /// 二次缓入缓出函数,起始和结束较慢,中间加速
314    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    /// Quint 缓出函数,起始快速后减速至停止
324    pub fn ease_out_quint() -> impl Fn(f32) -> f32 {
325        move |delta| 1.0 - (1.0 - delta).powi(5)
326    }
327
328    /// 应用给定的缓动函数,先正向再反向
329    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    /// 用于脉动 alpha 值的自定义缓动函数,在接近 0.1 时减速
340    pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
341        let range = max - min;
342
343        move |delta| {
344            // Use a combination of sine and cubic functions for a more natural breathing rhythm
345            let t = (delta * 2.0 * PI).sin();
346            let breath = (t * t * t + t) / 2.0;
347
348            // Map the breath to our desired alpha range
349            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            // 节流变体同步到共享时钟,因此 delta 跟随测试调度器的时钟
407            // 而不是墙钟时间。
408            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    // Before parent-animation-element, using .with_animation
455    // would not allow chaining .parent after. This is just a
456    // build check that we can call div().id().with_animation().child()
457    #[test]
458    fn test_animation_parent() {
459        div()
460            .id("id")
461            //
462            .with_animation(
463                "animation",
464                Animation::new(Duration::from_secs(1)),
465                |el, _t| {
466                    //
467                    el
468                },
469            )
470            .child(
471                //
472                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        // 测试调度器的时钟在每次轮询时会轻微向前跳动,
493        // 因此与预期值做宽松比较。
494        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        // 不会调度每帧回调;重渲染由定时器驱动。
508        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        // The second element mounts a quarter through the cycle, yet renders
542        // the shared phase rather than starting at zero.
543        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        // The phase wraps around each full cycle.
561        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        // Sub-second precision survives months of uptime: converting the raw
566        // elapsed time to f32 would round 0.25 away entirely.
567        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}