use std::{
collections::{HashMap, HashSet},
sync::OnceLock,
time::Duration,
};
use super::{
easing::Easing,
interpolate::write_property,
keyframes::{KeyframeEntry, Keyframes, KeyframesId},
};
use crate::{core::NodeId, time::Instant};
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationDirection {
Normal,
Reverse,
Alternate,
AlternateReverse,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationFillMode {
None,
Forwards,
Backwards,
Both,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AnimationIterationCount {
Count(f64),
Infinite,
}
#[derive(Clone, Debug)]
pub struct Animation {
pub keyframes: KeyframesId,
pub duration: Duration,
pub delay: Duration,
pub easing: Easing,
pub direction: AnimationDirection,
pub fill_mode: AnimationFillMode,
pub iteration_count: AnimationIterationCount,
}
impl Animation {
pub fn new(keyframes: impl Into<KeyframesId>) -> Self {
Self {
keyframes: keyframes.into(),
duration: Duration::from_millis(300),
delay: Duration::ZERO,
easing: Easing::EASE,
direction: AnimationDirection::Normal,
fill_mode: AnimationFillMode::None,
iteration_count: AnimationIterationCount::Count(1.0),
}
}
pub fn duration(mut self, d: Duration) -> Self {
self.duration = d;
self
}
pub fn duration_ms(mut self, ms: u64) -> Self {
self.duration = Duration::from_millis(ms);
self
}
pub fn delay(mut self, d: Duration) -> Self {
self.delay = d;
self
}
pub fn delay_ms(mut self, ms: u64) -> Self {
self.delay = Duration::from_millis(ms);
self
}
pub fn easing(mut self, e: Easing) -> Self {
self.easing = e;
self
}
pub fn linear(mut self) -> Self {
self.easing = Easing::Linear;
self
}
pub fn direction(mut self, d: AnimationDirection) -> Self {
self.direction = d;
self
}
pub fn fill_mode(mut self, f: AnimationFillMode) -> Self {
self.fill_mode = f;
self
}
pub fn iteration_count(mut self, c: AnimationIterationCount) -> Self {
self.iteration_count = c;
self
}
pub fn infinite(mut self) -> Self {
self.iteration_count = AnimationIterationCount::Infinite;
self
}
pub fn alternate(mut self) -> Self {
self.direction = AnimationDirection::Alternate;
self
}
pub(crate) fn total_time(&self) -> Duration {
let iterations = match self.iteration_count {
AnimationIterationCount::Count(count) if count.is_finite() && count > 0.0 => count,
AnimationIterationCount::Count(_) => 0.0,
AnimationIterationCount::Infinite => 1.0,
};
let active = Duration::try_from_secs_f64(self.duration.as_secs_f64() * iterations).unwrap_or(Duration::MAX);
self.delay.saturating_add(active)
}
}
const STEP_MARGIN: Duration = Duration::from_micros(100);
pub(super) fn step_time(now: Instant, duration: Duration, fraction: f64) -> Option<Instant> {
if !(fraction.is_finite() && fraction >= 0.0) {
return Some(now);
}
let offset = Duration::try_from_secs_f64(duration.as_secs_f64() * fraction).ok()?;
now.checked_add(offset)?.checked_add(STEP_MARGIN)
}
struct AnimationRun {
keyframes: KeyframesId,
duration: Duration,
delay: Duration,
easing: Easing,
direction: AnimationDirection,
fill_mode: AnimationFillMode,
iteration_count: f64,
start_time: Instant,
finished: bool,
}
enum Phase {
Delay,
Active { iteration: f64, progress: f64 },
Done,
}
impl AnimationRun {
fn phase(&self, now: Instant) -> Phase {
let elapsed = now.duration_since(self.start_time);
if elapsed < self.delay {
return Phase::Delay;
}
let duration = self.duration.as_secs_f64();
let active = (elapsed - self.delay).as_secs_f64();
if duration <= 0.0 || active >= duration * self.iteration_count {
return Phase::Done;
}
let iteration = (active / duration).floor();
Phase::Active {
iteration,
progress: active / duration - iteration,
}
}
fn final_progress(&self) -> Option<f64> {
let fills = matches!(self.fill_mode, AnimationFillMode::Forwards | AnimationFillMode::Both);
fills.then(|| {
let count = self.iteration_count.max(0.0);
let (iteration, progress) = match count.fract() {
_ if count == 0.0 => (0.0, 0.0),
_ if count.is_infinite() => (0.0, 1.0),
0.0 => (count - 1.0, 1.0),
fraction => (count.floor(), fraction),
};
directed_progress(progress, self.direction, iteration)
})
}
fn next_change(&self, frames: &[KeyframeEntry], now: Instant) -> Option<Instant> {
let (iteration, progress) = match self.phase(now) {
Phase::Delay => return Some(self.start_time + self.delay),
Phase::Done => return None,
Phase::Active { iteration, progress } => (iteration, progress),
};
let forward = plays_forward(self.direction, iteration);
let directed = if forward { progress } else { 1.0 - progress };
let Some(until_step) = distance_to_next_step(frames, directed, forward, &self.easing) else {
return Some(now);
};
let until_end = self.iteration_count - iteration - progress;
step_time(now, self.duration, until_step.min(until_end))
}
}
static CLOCK_ORIGIN: OnceLock<Instant> = OnceLock::new();
pub fn clock_origin() -> Instant {
*CLOCK_ORIGIN.get_or_init(Instant::now)
}
fn phase_period(direction: AnimationDirection, duration: Duration) -> u128 {
match direction {
AnimationDirection::Normal | AnimationDirection::Reverse => duration.as_nanos(),
AnimationDirection::Alternate | AnimationDirection::AlternateReverse => 2 * duration.as_nanos(),
}
}
fn start_time(in_phase: bool, direction: AnimationDirection, duration: Duration, now: Instant) -> Instant {
if !in_phase || duration.is_zero() {
return now;
}
let since_origin = now.saturating_duration_since(clock_origin());
let late = since_origin.as_nanos() % phase_period(direction, duration);
let late = u64::try_from(late).expect("the time since the animation clock's origin fits in u64 nanoseconds");
now - Duration::from_nanos(late)
}
fn spin() -> Keyframes {
use super::interpolate::AnimatableProperty;
use crate::node::transform::Decomposed;
Keyframes::new(crate::ui::SPIN)
.frame(0.0, |frame| {
frame.set(AnimatableProperty::Transform, Decomposed::IDENTITY);
})
.frame(1.0, |frame| {
frame.set(
AnimatableProperty::Transform,
Decomposed::IDENTITY.with_rotate_deg(360.0),
);
})
}
fn fade(id: KeyframesId, from: f32, to: f32) -> Keyframes {
use super::interpolate::{AnimatableProperty, AnimatableValue};
Keyframes::new(id)
.frame(0.0, |frame| {
frame.set(AnimatableProperty::Opacity, AnimatableValue::Float(from));
})
.frame(1.0, |frame| {
frame.set(AnimatableProperty::Opacity, AnimatableValue::Float(to));
})
}
pub struct AnimationEngine {
active: HashMap<(NodeId, KeyframesId), AnimationRun>,
keyframe_store: HashMap<KeyframesId, Vec<KeyframeEntry>>,
seen: HashSet<NodeId>,
next_change: Option<Instant>,
in_phase: HashSet<KeyframesId>,
resumed: HashMap<NodeId, f32>,
pub has_active: bool,
}
impl Default for AnimationEngine {
fn default() -> Self {
Self::new()
}
}
impl AnimationEngine {
pub fn new() -> Self {
let mut engine = Self {
active: HashMap::new(),
keyframe_store: HashMap::new(),
seen: HashSet::new(),
next_change: None,
in_phase: HashSet::new(),
resumed: HashMap::new(),
has_active: false,
};
engine.register_keyframes_in_phase(spin());
engine.register_keyframes(fade(crate::ui::FADE_IN, 0.0, 1.0));
engine.register_keyframes(fade(crate::ui::FADE_OUT, 1.0, 0.0));
for keyframes in crate::ui::toast_keyframes() {
engine.register_keyframes(keyframes);
}
for keyframes in crate::ui::spinner_keyframes()
.into_iter()
.chain(crate::ui::skeleton_keyframes())
{
engine.register_keyframes_in_phase(keyframes);
}
for keyframes in crate::ui::progress_keyframes() {
engine.register_keyframes_in_phase(keyframes);
}
for keyframes in crate::ui::input_otp_keyframes() {
engine.register_keyframes(keyframes);
}
for keyframes in crate::ui::sheet_keyframes() {
engine.register_keyframes(keyframes);
}
engine
}
pub fn register_keyframes(&mut self, keyframes: Keyframes) {
self.in_phase.remove(&keyframes.id);
self.keyframe_store.insert(keyframes.id, keyframes.frames);
}
pub fn register_keyframes_in_phase(&mut self, keyframes: Keyframes) {
self.in_phase.insert(keyframes.id);
self.keyframe_store.insert(keyframes.id, keyframes.frames);
}
pub(crate) fn forget_node(&mut self, node: NodeId) {
self.active.retain(|(id, _), _| *id != node);
if let Some(done) = self.resumed.get_mut(&node) {
*done = 1.0 - *done;
}
}
pub(crate) fn turn_round(&mut self, nodes: &[NodeId], now: Instant) {
let nodes: HashSet<NodeId> = nodes.iter().copied().collect();
let mut resumed = Vec::new();
self.active.retain(|(node, _), run| {
if !nodes.contains(node) {
return true;
}
let played = if run.finished || run.duration.is_zero() {
1.0
} else {
let elapsed = now.saturating_duration_since(run.start_time + run.delay);
(elapsed.as_secs_f32() / run.duration.as_secs_f32()).clamp(0.0, 1.0)
};
resumed.push((*node, 1.0 - played));
false
});
self.resumed.extend(resumed);
}
pub(crate) fn clear_state(&mut self) {
self.resumed.clear();
self.active.clear();
self.seen.clear();
self.next_change = None;
self.has_active = false;
}
pub(crate) fn begin_frame(&mut self) {
self.seen.clear();
self.next_change = None;
}
pub(crate) fn finish_frame(&mut self) {
let seen = &self.seen;
self.active.retain(|(node_id, _), _| seen.contains(node_id));
self.resumed.retain(|node_id, _| seen.contains(node_id));
self.has_active = self.active.values().any(|run| !run.finished);
}
pub(crate) fn next_change(&self) -> Option<Instant> {
self.next_change
}
pub(crate) fn tick(&mut self, root: &mut crate::node::Node, now: Instant) -> bool {
self.has_active = false;
let needs_layout = self.tick_recursive(root, now);
self.has_active = self.active.values().any(|run| !run.finished);
needs_layout
}
pub(crate) fn tick_preserving_active_state(&mut self, root: &mut crate::node::Node, now: Instant) -> bool {
let needs_layout = self.tick_recursive(root, now);
self.has_active = self.active.values().any(|run| !run.finished);
needs_layout
}
fn tick_recursive(&mut self, node: &mut crate::node::Node, now: Instant) -> bool {
if !node.prepare_layout_tracking().animations {
return false;
}
#[cfg(test)]
crate::core::layout_dirty::visit();
let mut needs_layout = false;
let node_id = node.node_id();
if node_id.is_assigned()
&& let Some(spec) = node.playing_animation()
{
self.seen.insert(node_id);
let spec = Animation::clone(spec);
needs_layout = self.process_node(node, &spec, now);
}
for child in &mut node.children {
if self.tick_recursive(child, now) {
needs_layout = true;
}
}
if needs_layout {
node.layout_cache.invalidate();
}
needs_layout
}
fn process_node(&mut self, node: &mut crate::node::Node, spec: &Animation, now: Instant) -> bool {
let node_id = node.node_id();
let key = (node_id, spec.keyframes);
let iteration_count = match spec.iteration_count {
AnimationIterationCount::Count(c) => c,
AnimationIterationCount::Infinite => f64::INFINITY,
};
let in_phase = self.in_phase.contains(&spec.keyframes);
let done = if self.active.contains_key(&key) {
None
} else {
self.resumed.remove(&node_id)
};
let run = self.active.entry(key).or_insert_with(|| AnimationRun {
keyframes: spec.keyframes,
duration: spec.duration,
delay: spec.delay,
easing: spec.easing,
direction: spec.direction,
fill_mode: spec.fill_mode,
iteration_count,
start_time: match done {
Some(done) => now.checked_sub(spec.duration.mul_f32(done) + spec.delay).unwrap_or(now),
None => start_time(in_phase, spec.direction, spec.duration, now),
},
finished: false,
});
let frames = match self.keyframe_store.get(&run.keyframes) {
Some(f) => f,
None => return false,
};
if run.finished {
if let Some(progress) = run.final_progress() {
apply_keyframe_at(node, frames, progress as f32, &run.easing);
}
return false;
}
let layout_affected = match run.phase(now) {
Phase::Delay => {
matches!(run.fill_mode, AnimationFillMode::Backwards | AnimationFillMode::Both)
&& apply_keyframe_at(
node,
frames,
directed_progress(0.0, run.direction, 0.0) as f32,
&run.easing,
)
}
Phase::Done => {
run.finished = true;
run
.final_progress()
.is_some_and(|progress| apply_keyframe_at(node, frames, progress as f32, &run.easing))
}
Phase::Active { iteration, progress } => {
let progress = directed_progress(progress, run.direction, iteration);
apply_keyframe_at(node, frames, progress as f32, &run.easing)
}
};
if let Some(at) = run.next_change(frames, now) {
self.next_change = Some(self.next_change.map_or(at, |next| next.min(at)));
}
layout_affected
}
}
fn plays_forward(direction: AnimationDirection, iteration: f64) -> bool {
let even = (iteration as u64).is_multiple_of(2);
match direction {
AnimationDirection::Normal => true,
AnimationDirection::Reverse => false,
AnimationDirection::Alternate => even,
AnimationDirection::AlternateReverse => !even,
}
}
fn directed_progress(progress: f64, direction: AnimationDirection, iteration: f64) -> f64 {
if plays_forward(direction, iteration) {
progress
} else {
1.0 - progress
}
}
fn distance_to_next_step(
frames: &[KeyframeEntry],
progress: f64,
forward: bool,
overall_easing: &Easing,
) -> Option<f64> {
let (lo, hi) = find_surrounding_frames(frames, progress as f32);
if lo == hi {
return None;
}
let (lo_frame, hi_frame) = (&frames[lo], &frames[hi]);
let span = f64::from(hi_frame.offset - lo_frame.offset);
if span <= 0.0 {
return None;
}
let local = (progress - f64::from(lo_frame.offset)) / span;
let easing = lo_frame.easing.as_ref().unwrap_or(overall_easing);
easing
.distance_to_next_step(local, forward)
.map(|distance| distance * span)
}
fn apply_keyframe_at(
node: &mut crate::node::Node,
frames: &[KeyframeEntry],
progress: f32,
overall_easing: &Easing,
) -> bool {
if frames.is_empty() {
return false;
}
let mut layout_affected = false;
let (lo, hi) = find_surrounding_frames(frames, progress);
let lo_frame = &frames[lo];
let hi_frame = &frames[hi];
if lo == hi {
for (prop, value) in &lo_frame.values {
layout_affected |= write_property(node, *prop, value);
}
return layout_affected;
}
let span = hi_frame.offset - lo_frame.offset;
let local = if span > 0.0 {
((progress - lo_frame.offset) / span).clamp(0.0, 1.0)
} else {
1.0
};
let easing = lo_frame.easing.as_ref().unwrap_or(overall_easing);
let t = easing.evaluate(local as f64) as f32;
for (prop, lo_val) in &lo_frame.values {
if let Some((_, hi_val)) = hi_frame.values.iter().find(|(p, _)| p == prop) {
let interpolated = lo_val.lerp(hi_val, t);
layout_affected |= write_property(node, *prop, &interpolated);
} else {
layout_affected |= write_property(node, *prop, lo_val);
}
}
layout_affected
}
fn find_surrounding_frames(frames: &[KeyframeEntry], progress: f32) -> (usize, usize) {
if frames.len() == 1 {
return (0, 0);
}
for (i, frame) in frames.iter().enumerate().skip(1) {
if frame.offset >= progress {
return (i - 1, i);
}
}
let last = frames.len() - 1;
(last, last)
}