use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Easing {
#[default]
Linear,
EaseInQuad,
EaseOutQuad,
EaseInOutQuad,
EaseInCubic,
EaseOutCubic,
EaseInOutCubic,
}
impl Easing {
pub fn apply(self, t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
match self {
Easing::Linear => t,
Easing::EaseInQuad => t * t,
Easing::EaseOutQuad => 1.0 - (1.0 - t) * (1.0 - t),
Easing::EaseInOutQuad => {
if t < 0.5 {
2.0 * t * t
} else {
1.0 - 2.0 * (1.0 - t) * (1.0 - t)
}
}
Easing::EaseInCubic => t * t * t,
Easing::EaseOutCubic => {
let u = 1.0 - t;
1.0 - u * u * u
}
Easing::EaseInOutCubic => {
if t < 0.5 {
4.0 * t * t * t
} else {
let u = -2.0 * t + 2.0;
1.0 - u * u * u / 2.0
}
}
}
}
}
#[derive(Clone, Debug)]
pub struct Animate {
from: f32,
to: f32,
duration: Duration,
elapsed: Duration,
easing: Easing,
done: bool,
}
impl Animate {
pub fn new(from: f32, to: f32, duration: Duration, easing: Easing) -> Self {
Self {
from,
to,
duration,
elapsed: Duration::ZERO,
easing,
done: duration.is_zero(),
}
}
pub fn tick(&mut self, dt: Duration) -> bool {
if self.done {
return false;
}
self.elapsed = (self.elapsed + dt).min(self.duration);
if self.elapsed >= self.duration {
self.done = true;
return false;
}
true
}
pub fn value(&self) -> f32 {
if self.duration.is_zero() {
return self.to;
}
let t = self.elapsed.as_secs_f32() / self.duration.as_secs_f32();
let e = self.easing.apply(t);
self.from + (self.to - self.from) * e
}
pub fn progress(&self) -> f32 {
if self.duration.is_zero() {
return 1.0;
}
self.easing
.apply(self.elapsed.as_secs_f32() / self.duration.as_secs_f32())
}
pub fn is_done(&self) -> bool {
self.done
}
pub fn target(&self) -> f32 {
self.to
}
pub fn retarget(&self, to: f32, duration: Duration, easing: Easing) -> Self {
Self::new(self.value(), to, duration, easing)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn event_ctx_start_animation_pushes_request() {
use crate::widget::EventCtx;
let mut ctx = EventCtx::new(None, crate::geometry::Size::new(100.0, 100.0));
let key = key_of("probe");
assert!(ctx.anim_requests.is_empty());
ctx.start_animation(
key,
Animate::new(
0.0,
1.0,
std::time::Duration::from_millis(120),
Easing::EaseOutCubic,
),
);
assert_eq!(ctx.anim_requests.len(), 1);
assert_eq!(ctx.anim_requests[0].0, key);
}
#[test]
fn start_animation_marks_redraw_and_is_drainable() {
use crate::widget::EventCtx;
let mut ctx = EventCtx::new(None, crate::geometry::Size::new(10.0, 10.0));
assert!(!ctx.redraw, "初始不应要求重绘");
ctx.start_animation(
key_of("x"),
Animate::new(
0.0,
1.0,
std::time::Duration::from_millis(80),
Easing::Linear,
),
);
assert!(ctx.redraw, "请求动画应顺带标记重绘");
let drained: Vec<(u64, Animate)> = std::mem::take(&mut ctx.anim_requests);
assert_eq!(drained.len(), 1);
assert!(ctx.anim_requests.is_empty());
}
#[test]
fn linear_easing_is_identity() {
for i in 0..=10 {
let t = i as f32 / 10.0;
assert!((Easing::Linear.apply(t) - t).abs() < 1e-6);
}
}
#[test]
fn easing_endpoints_and_monotonicity() {
let all = [
Easing::Linear,
Easing::EaseInQuad,
Easing::EaseOutQuad,
Easing::EaseInOutQuad,
Easing::EaseInCubic,
Easing::EaseOutCubic,
Easing::EaseInOutCubic,
];
for e in all {
assert!((e.apply(0.0) - 0.0).abs() < 1e-6, "{e:?} 起点应为 0");
assert!((e.apply(1.0) - 1.0).abs() < 1e-6, "{e:?} 终点应为 1");
let mut prev = -1.0;
for i in 0..=100 {
let v = e.apply(i as f32 / 100.0);
assert!(v >= prev - 1e-6, "{e:?} 在 t={} 处非单调", i as f32 / 100.0);
prev = v;
}
}
}
#[test]
fn ease_in_starts_slow_and_out_starts_fast() {
assert!(Easing::EaseInCubic.apply(0.25) < 0.25);
assert!(Easing::EaseOutCubic.apply(0.25) > 0.25);
assert!((Easing::EaseInOutCubic.apply(0.5) - 0.5).abs() < 1e-5);
}
#[test]
fn animate_interpolates_and_finishes() {
let mut a = Animate::new(0.0, 100.0, Duration::from_millis(100), Easing::Linear);
assert_eq!(a.value(), 0.0);
assert!(a.tick(Duration::from_millis(50)));
assert!(
(a.value() - 50.0).abs() < 0.5,
"一半时应约为 50,实际 {}",
a.value()
);
assert!(!a.tick(Duration::from_millis(60)), "超时后应完成");
assert!(a.is_done());
assert!((a.value() - 100.0).abs() < 1e-3, "完成后应为终值");
}
#[test]
fn ticking_a_finished_animation_is_a_no_op() {
let mut a = Animate::new(0.0, 1.0, Duration::from_millis(10), Easing::Linear);
assert!(!a.tick(Duration::from_millis(20)));
assert!(!a.tick(Duration::from_millis(20)));
assert!(!a.tick(Duration::from_millis(20)));
assert!(a.is_done());
}
#[test]
fn retarget_continues_from_current_value_without_jumping_back() {
let mut a = Animate::new(0.0, 100.0, Duration::from_millis(100), Easing::Linear);
a.tick(Duration::from_millis(40));
let mid = a.value();
assert!((mid - 40.0).abs() < 1.0);
let b = a.retarget(0.0, Duration::from_millis(100), Easing::Linear);
assert!(
(b.value() - mid).abs() < 1e-3,
"打断后应从当前值接续,实际 {} vs {}",
b.value(),
mid
);
assert_eq!(b.target(), 0.0);
}
#[test]
fn zero_duration_completes_immediately() {
let a = Animate::new(5.0, 9.0, Duration::ZERO, Easing::Linear);
assert!(a.is_done(), "零时长应立即完成");
assert_eq!(a.value(), 9.0);
assert_eq!(a.progress(), 1.0);
}
#[test]
fn progress_tracks_easing_not_raw_time() {
let mut a = Animate::new(0.0, 1.0, Duration::from_millis(100), Easing::EaseOutCubic);
a.tick(Duration::from_millis(50));
let p = a.progress();
assert!(p > 0.5, "减速曲线一半时应过半(实际 {p})");
assert!(p < 1.0);
}
}
pub fn key_of(id: &str) -> u64 {
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
for b in id.as_bytes() {
h ^= *b as u64;
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
h
}
pub const POPUP_OPEN_MS: u64 = 150;
#[derive(Clone, Debug, Default)]
pub struct AnimSnapshot {
entries: Vec<(u64, f32)>,
}
impl AnimSnapshot {
pub fn new(entries: Vec<(u64, f32)>) -> Self {
Self { entries }
}
pub fn get(&self, key: u64) -> Option<f32> {
self.entries
.iter()
.find(|(k, _)| *k == key)
.map(|(_, v)| *v)
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}