Skip to main content

repose_ui/
anim.rs

1use std::cell::RefCell;
2use std::rc::Rc;
3
4use repose_core::{
5    Color, Rect, Size, Vec2,
6    animation::{AnimatedValue, AnimationSpec, KeyframesSpec, RepeatableSpec, SplineKeyframes},
7    animation_driver, remember_state_with_key, request_frame,
8};
9
10/// Animate f32 from an explicit initial value to a target.
11/// - On first creation for this key, starts at `initial` then animates toward `target`.
12/// - On later calls, animates from the current value to the new target.
13pub fn animate_f32_from(
14    key: impl Into<String>,
15    initial: f32,
16    target: f32,
17    spec: AnimationSpec,
18) -> f32 {
19    let key = key.into();
20    let anim_key = format!("anim:f32:{key}");
21    let anim = remember_state_with_key(&anim_key, || AnimatedValue::new(initial, spec));
22    let last = remember_state_with_key(format!("anim:f32_last:{key}"), || f32::NAN);
23
24    // Doesn't remove entries from pages that are still being composed with this.
25    animation_driver::touch(&anim_key);
26
27    let mut a = anim.borrow_mut();
28    let mut lt = last.borrow_mut();
29    let should_set_target = lt.is_nan() || (*lt - target).abs() > 1e-6;
30    if should_set_target {
31        a.set_spec(spec);
32        a.set_target(target);
33        *lt = target;
34        drop(lt);
35
36        // Register with AnimationDriver for pre-composition advancement.
37        let reg_key = anim_key;
38        let reg_anim = anim.clone();
39        animation_driver::register(
40            reg_key,
41            Rc::new(RefCell::new(move || reg_anim.borrow_mut().update())),
42        );
43        request_frame();
44
45        *a.get()
46    } else {
47        let needs_reregister = !animation_driver::is_registered(&anim_key) && a.is_animating();
48        let cur = *a.get();
49        drop(lt);
50        drop(a);
51        if needs_reregister {
52            let reg_anim = anim.clone();
53            animation_driver::register(
54                anim_key,
55                Rc::new(RefCell::new(move || reg_anim.borrow_mut().update())),
56            );
57            request_frame();
58        }
59        cur
60    }
61}
62
63/// Animate f32 to target. Starts at target on first mount.
64pub fn animate_f32(key: impl Into<String>, target: f32, spec: AnimationSpec) -> f32 {
65    animate_f32_from(key, target, target, spec)
66}
67
68/// Animate f32 to target, snapping immediately while `snap` is true.
69pub fn animate_f32_snapping(
70    key: impl Into<String>,
71    target: f32,
72    snap: bool,
73    spec: AnimationSpec,
74) -> f32 {
75    let key = key.into();
76    let anim_key = format!("anim:f32:{key}");
77    let anim = remember_state_with_key(&anim_key, || AnimatedValue::new(target, spec));
78    let last = remember_state_with_key(format!("anim:f32_last:{key}"), || f32::NAN);
79    animation_driver::touch(&anim_key);
80    let should_set = {
81        let last = last.borrow();
82        last.is_nan() || (*last - target).abs() > 1e-6
83    };
84    if should_set {
85        *last.borrow_mut() = target;
86        {
87            let mut value = anim.borrow_mut();
88            value.set_spec(spec);
89            if snap {
90                value.snap_to(target);
91            } else {
92                value.set_target(target);
93            }
94        }
95        let registration = anim.clone();
96        animation_driver::register(
97            anim_key.clone(),
98            Rc::new(RefCell::new(move || registration.borrow_mut().update())),
99        );
100        request_frame();
101    } else if !animation_driver::is_registered(&anim_key) && anim.borrow().is_animating() {
102        let registration = anim.clone();
103        animation_driver::register(
104            anim_key.clone(),
105            Rc::new(RefCell::new(move || registration.borrow_mut().update())),
106        );
107        request_frame();
108    }
109    *anim.borrow().get()
110}
111
112macro_rules! animate_from_impl {
113    ($name:ident, $type:ty, $prefix:expr) => {
114        pub fn $name(
115            key: impl Into<String>,
116            initial: $type,
117            target: $type,
118            spec: AnimationSpec,
119        ) -> $type {
120            let key = key.into();
121            let anim_key = format!("anim:{}:{}", $prefix, key);
122            let anim = remember_state_with_key(&anim_key, || AnimatedValue::new(initial, spec));
123            let last =
124                remember_state_with_key(format!("anim:{}_last:{}", $prefix, key), || None::<$type>);
125
126            repose_core::animation_driver::touch(&anim_key);
127
128            let mut a = anim.borrow_mut();
129            let mut lt = last.borrow_mut();
130            if lt.is_none() || lt.as_ref().unwrap() != &target {
131                a.set_spec(spec);
132                a.set_target(target);
133                *lt = Some(target);
134                drop(lt);
135
136                // Register with AnimationDriver
137                let reg_key = anim_key.clone();
138                let reg_anim = anim.clone();
139                repose_core::animation_driver::register(
140                    reg_key,
141                    std::rc::Rc::new(std::cell::RefCell::new(move || {
142                        reg_anim.borrow_mut().update()
143                    })),
144                );
145                repose_core::request_frame();
146
147                *a.get()
148            } else {
149                let needs_reregister =
150                    !repose_core::animation_driver::is_registered(&anim_key) && a.is_animating();
151                let cur = *a.get();
152                drop(lt);
153                drop(a);
154                if needs_reregister {
155                    let reg_anim = anim.clone();
156                    repose_core::animation_driver::register(
157                        anim_key,
158                        std::rc::Rc::new(std::cell::RefCell::new(move || {
159                            reg_anim.borrow_mut().update()
160                        })),
161                    );
162                    repose_core::request_frame();
163                }
164                cur
165            }
166        }
167    };
168}
169
170animate_from_impl!(animate_color_from, Color, "color");
171animate_from_impl!(animate_vec2_from, Vec2, "vec2");
172animate_from_impl!(animate_size_from, Size, "size");
173animate_from_impl!(animate_rect_from, Rect, "rect");
174
175/// Animate Color to target. Starts at target on first mount.
176pub fn animate_color(key: impl Into<String>, target: Color, spec: AnimationSpec) -> Color {
177    animate_color_from(key, target, target, spec)
178}
179
180/// Animate Color with a different spec when entering and leaving `active`.
181pub fn animate_color_directional(
182    key: impl Into<String>,
183    target: Color,
184    active: bool,
185    enter_spec: AnimationSpec,
186    exit_spec: AnimationSpec,
187) -> Color {
188    let key = key.into();
189    let anim_key = format!("anim:color:{key}");
190    let spec = if active { enter_spec } else { exit_spec };
191    let anim = remember_state_with_key(&anim_key, || AnimatedValue::new(target, spec));
192    let last =
193        remember_state_with_key(
194            format!("anim:color_dir_last:{key}"),
195            || None::<(Color, bool)>,
196        );
197    animation_driver::touch(&anim_key);
198    let mut value = anim.borrow_mut();
199    let mut previous = last.borrow_mut();
200    if previous
201        .as_ref()
202        .is_none_or(|(color, was_active)| *color != target || *was_active != active)
203    {
204        value.set_spec(spec);
205        value.set_target(target);
206        *previous = Some((target, active));
207        drop(previous);
208        let registration = anim.clone();
209        animation_driver::register(
210            anim_key.clone(),
211            Rc::new(RefCell::new(move || registration.borrow_mut().update())),
212        );
213        drop(value);
214        request_frame();
215    } else {
216        let needs_reregister = !animation_driver::is_registered(&anim_key) && value.is_animating();
217        drop(previous);
218        drop(value);
219        if needs_reregister {
220            let registration = anim.clone();
221            animation_driver::register(
222                anim_key,
223                Rc::new(RefCell::new(move || registration.borrow_mut().update())),
224            );
225            request_frame();
226        }
227    }
228    *anim.borrow().get()
229}
230
231/// Animate Vec2 to target. Starts at target on first mount.
232pub fn animate_vec2(key: impl Into<String>, target: Vec2, spec: AnimationSpec) -> Vec2 {
233    animate_vec2_from(key, target, target, spec)
234}
235
236/// Animate Size to target. Starts at target on first mount.
237pub fn animate_size(key: impl Into<String>, target: Size, spec: AnimationSpec) -> Size {
238    animate_size_from(key, target, target, spec)
239}
240
241/// Animate Rect to target. Starts at target on first mount.
242pub fn animate_rect(key: impl Into<String>, target: Rect, spec: AnimationSpec) -> Rect {
243    animate_rect_from(key, target, target, spec)
244}
245
246/// Animate f32 through a sequence of keyframes.
247///
248/// The keyframe timestamps range from 0.0 to 1.0, mapped across `spec`'s duration.
249/// The animation loops if `repeat` is set on the spec.
250///
251/// Example:
252/// ```ignore
253/// let val = animate_keyframes("bounce", KeyframesSpec::new(vec![
254///     (0.0, 0.0),
255///     (0.3, 100.0),
256///     (0.6, 80.0),
257///     (1.0, 100.0),
258/// ]), AnimationSpec::tween(Duration::from_millis(600), Easing::EaseOut));
259/// ```
260pub fn animate_keyframes(
261    key: impl Into<String>,
262    keyframes: KeyframesSpec<f32>,
263    spec: AnimationSpec,
264) -> f32 {
265    let key = key.into();
266    let anim_key = format!("anim:kf:{key}");
267    let anim = remember_state_with_key(&anim_key, || AnimatedValue::new(0.0, spec));
268    let last = remember_state_with_key(format!("anim:kf_last:{key}"), || None::<String>);
269    animation_driver::touch(&anim_key);
270
271    let fingerprint = format!("{:?}|{:?}", keyframes.keyframes, spec);
272    let should_restart = {
273        let lt = last.borrow();
274        lt.as_ref() != Some(&fingerprint)
275    };
276    let mut a = anim.borrow_mut();
277    if should_restart {
278        a.set_spec(spec);
279        a.set_keyframes(keyframes);
280        *last.borrow_mut() = Some(fingerprint);
281        drop(a);
282        let reg_anim = anim.clone();
283        animation_driver::register(
284            anim_key.clone(),
285            Rc::new(RefCell::new(move || reg_anim.borrow_mut().update())),
286        );
287        request_frame();
288        *anim.borrow().get()
289    } else {
290        let needs_reregister = !animation_driver::is_registered(&anim_key) && a.is_animating();
291        let cur = *a.get();
292        drop(a);
293        if needs_reregister {
294            let reg_anim = anim.clone();
295            animation_driver::register(
296                anim_key,
297                Rc::new(RefCell::new(move || reg_anim.borrow_mut().update())),
298            );
299            request_frame();
300        }
301        cur
302    }
303}
304
305/// Animate f32 through a sequence of keyframes using a smooth cubic Hermite spline.
306///
307/// Produces C1-continuous animation (smooth derivatives at keyframe boundaries),
308/// unlike `animate_keyframes` which uses C0 linear interpolation.
309///
310/// Example:
311/// ```ignore
312/// let val = animate_spline_keyframes("bounce", SplineKeyframes::new(vec![
313///     (0.0, 0.0),
314///     (0.3, 100.0),
315///     (0.6, 80.0),
316///     (1.0, 100.0),
317/// ]), AnimationSpec::tween(Duration::from_millis(600), Easing::EaseInOut));
318/// ```
319pub fn animate_spline_keyframes(
320    key: impl Into<String>,
321    keyframes: SplineKeyframes,
322    spec: AnimationSpec,
323) -> f32 {
324    let key = key.into();
325    // Animate progress 0..1 using standard AnimatedValue (handles easing, repeat, frame clock)
326    let anim = remember_state_with_key(format!("anim:spkf_progress:{key}"), || {
327        AnimatedValue::new(0.0, spec)
328    });
329    let spline = remember_state_with_key(format!("anim:spkf:{key}"), || keyframes.clone());
330
331    let anim_key = format!("anim:spkf_progress:{key}");
332    let last = remember_state_with_key(format!("anim:spkf_last:{key}"), || None::<String>);
333    animation_driver::touch(&anim_key);
334    let fingerprint = format!("{}|{spec:?}", keyframes.fingerprint());
335    let should_restart = {
336        let lt = last.borrow();
337        lt.as_ref() != Some(&fingerprint)
338    };
339
340    let progress = {
341        let mut a = anim.borrow_mut();
342        if should_restart {
343            a.set_spec(spec);
344            a.set_target(1.0);
345            *last.borrow_mut() = Some(fingerprint);
346            *spline.borrow_mut() = keyframes;
347            drop(a);
348            let reg_anim = anim.clone();
349            animation_driver::register(
350                anim_key.clone(),
351                Rc::new(RefCell::new(move || reg_anim.borrow_mut().update())),
352            );
353            request_frame();
354            *anim.borrow().get()
355        } else {
356            let needs_reregister = !animation_driver::is_registered(&anim_key) && a.is_animating();
357            let cur = *a.get();
358            drop(a);
359            if needs_reregister {
360                let reg_anim = anim.clone();
361                animation_driver::register(
362                    anim_key,
363                    Rc::new(RefCell::new(move || reg_anim.borrow_mut().update())),
364                );
365                request_frame();
366            }
367            cur
368        }
369    };
370    spline.borrow().evaluate(progress)
371}
372
373fn with_infinite_repeat(spec: AnimationSpec) -> AnimationSpec {
374    if spec.repeat.is_none() {
375        spec.repeated(RepeatableSpec::infinite().reverse())
376    } else {
377        spec
378    }
379}
380
381/// A scoped API for continuous/repeating animations.
382///
383/// All child animations created via this transition loop indefinitely
384/// between the given initial and target values (ping-pong with `reverse`).
385///
386/// If you need a custom repeat configuration, pass an `AnimationSpec` that
387/// already has `.repeated(...)` set - the transition will respect it instead
388/// of applying the default infinite reverse.
389pub struct InfiniteTransition {
390    _private: (),
391}
392
393/// `InfiniteTransition` scoped to the current composition slot.
394///
395/// Use its `animate_float`, `animate_color`, `animate_vec2`, `animate_size`,
396/// and `animate_rect` methods for continuous looping animations.
397///
398/// # Example
399///
400/// ```ignore
401/// let t = remember_infinite_transition();
402/// let pulse = t.animate_float("pulse", 0.0, 1.0,
403///     AnimationSpec::tween(Duration::from_millis(600), Easing::EaseInOut));
404/// ```
405pub fn remember_infinite_transition() -> InfiniteTransition {
406    InfiniteTransition { _private: () }
407}
408
409macro_rules! inf_method {
410    ($method:ident, $from_fn:ident, $type:ty) => {
411        pub fn $method(
412            &self,
413            key: impl Into<String>,
414            initial: $type,
415            target: $type,
416            spec: AnimationSpec,
417        ) -> $type {
418            let key = key.into();
419            $from_fn(
420                format!("inf:{}", key),
421                initial,
422                target,
423                with_infinite_repeat(spec),
424            )
425        }
426    };
427}
428
429impl InfiniteTransition {
430    inf_method!(animate_float, animate_f32_from, f32);
431    inf_method!(animate_color, animate_color_from, Color);
432    inf_method!(animate_vec2, animate_vec2_from, Vec2);
433    inf_method!(animate_size, animate_size_from, Size);
434    inf_method!(animate_rect, animate_rect_from, Rect);
435}
436
437/// A scope for multi-target animations driven by a changing state.
438///
439/// When the target state changes (detected via `PartialEq`), all child
440/// animations registered via `animate_float`, `animate_color`, etc.
441/// automatically animate from their current value toward the new mapped
442/// target value.
443///
444/// # Example
445///
446/// ```ignore
447/// let t = update_transition("panel", is_expanded, AnimationSpec::spring_gentle());
448/// let h  = t.animate_float("height", |e| if *e { 200.0 } else { 48.0 });
449/// let bg = t.animate_color("bg", |e| if *e { theme().primary } else { theme().surface });
450/// ```
451pub struct TransitionScope<T> {
452    key: String,
453    spec: AnimationSpec,
454    state: Rc<RefCell<T>>,
455}
456
457/// `TransitionScope` keyed to the given state.
458///
459/// Whenever `target_state` differs from the previous call (via `PartialEq`),
460/// all child animation targets are updated and the transition animates toward
461/// the new values.
462pub fn update_transition<T>(
463    key: impl Into<String>,
464    target_state: T,
465    spec: AnimationSpec,
466) -> TransitionScope<T>
467where
468    T: PartialEq + Clone + 'static,
469{
470    let key = key.into();
471    let state: Rc<RefCell<T>> =
472        remember_state_with_key(format!("tr_state:{key}"), || target_state.clone());
473    if *state.borrow() != target_state {
474        *state.borrow_mut() = target_state;
475    }
476    TransitionScope { key, spec, state }
477}
478
479macro_rules! tr_method {
480    ($method:ident, $fn:ident, $type:ty) => {
481        pub fn $method<F>(&self, child_key: impl Into<String>, map: F) -> $type
482        where
483            F: Fn(&T) -> $type,
484        {
485            let target = map(&*self.state.borrow());
486            $fn(
487                format!("tr:{}:{}", self.key, child_key.into()),
488                target,
489                self.spec,
490            )
491        }
492    };
493}
494
495impl<T> TransitionScope<T> {
496    tr_method!(animate_float, animate_f32, f32);
497    tr_method!(animate_color, animate_color, Color);
498    tr_method!(animate_vec2, animate_vec2, Vec2);
499    tr_method!(animate_size, animate_size, Size);
500    tr_method!(animate_rect, animate_rect, Rect);
501}