use std::{
cell::Cell,
fmt,
rc::{Rc, Weak},
};
use super::{
AdaptiveColor,
reactive::{Kept, Owner},
task::{Action, Answer, Executor},
};
use crate::animation::{
AnimationId, AnimationOp, Composite, Driver, Easing, Extrapolate, Keyframe, KeyframeTiming,
MathOp, MotionChannel, MotionSpec, Operand, Output, StaggerFrom,
};
pub(crate) struct Node {
id: crate::animation::NodeId,
executor: Weak<Executor>,
_inputs: Vec<Rc<Node>>,
}
impl Node {
fn new(
executor: &Rc<Executor>,
op: impl FnOnce(crate::animation::NodeId) -> AnimationOp,
inputs: Vec<Rc<Node>>,
) -> Rc<Self> {
let id = executor.next_animation_id();
executor.act(Action::Animation(op(id)));
Rc::new(Self {
id,
executor: Rc::downgrade(executor),
_inputs: inputs,
})
}
fn act(&self, op: AnimationOp) {
if let Some(executor) = self.executor.upgrade() {
executor.act(Action::Animation(op));
}
}
}
impl Drop for Node {
fn drop(&mut self) {
self.act(AnimationOp::Release { node: self.id });
}
}
fn with_node(mut op: AnimationOp, id: crate::animation::NodeId) -> AnimationOp {
match &mut op {
AnimationOp::CreateValue { node, .. }
| AnimationOp::CreateInterpolate { node, .. }
| AnimationOp::CreateDiffClamp { node, .. }
| AnimationOp::CreateMath { node, .. } => *node = id,
_ => {}
}
op
}
#[derive(Default)]
pub(crate) struct Derived {
by_hash: rustc_hash::FxHashMap<u64, Vec<DerivedNode>>,
added: usize,
live: usize,
}
#[derive(Clone, PartialEq)]
struct DerivedKey {
op: AnimationOp,
dark: Option<Output>,
}
struct DerivedNode {
key: DerivedKey,
node: Weak<Node>,
handles: Vec<(Owner, AnimatedNode)>,
}
impl DerivedKey {
fn hash(&self) -> u64 {
use std::hash::{Hash, Hasher};
fn number(h: &mut rustc_hash::FxHasher, v: f32) {
(if v == 0.0 { 0 } else { v.to_bits() }).hash(h);
}
fn operand(h: &mut rustc_hash::FxHasher, o: &Operand) {
match *o {
Operand::Node(n) => n.hash(h),
Operand::Const(c) => number(h, c),
}
}
let mut h = rustc_hash::FxHasher::default();
std::mem::discriminant(&self.op).hash(&mut h);
match &self.op {
AnimationOp::CreateInterpolate {
input,
input_range,
output,
..
} => {
input.hash(&mut h);
input_range.iter().for_each(|&v| number(&mut h, v));
match output {
Output::Numbers(v) => v.iter().for_each(|&v| number(&mut h, v)),
Output::Colors(v) => v.hash(&mut h),
}
}
AnimationOp::CreateMath { a, b, .. } => {
operand(&mut h, a);
operand(&mut h, b);
}
AnimationOp::CreateDiffClamp {
input, min, max, ..
} => {
input.hash(&mut h);
operand(&mut h, min);
operand(&mut h, max);
}
_ => {}
}
h.finish()
}
}
impl Derived {
fn entry(&mut self, key: &DerivedKey) -> Option<&mut DerivedNode> {
let same = self.by_hash.get_mut(&key.hash())?;
same.retain(|d| d.node.strong_count() > 0);
same.iter_mut().find(|d| d.key == *key)
}
fn add(&mut self, node: DerivedNode) {
self.added += 1;
if self.added > self.live.max(64) {
self.by_hash.retain(|_, same| {
same.retain(|d| d.node.strong_count() > 0);
!same.is_empty()
});
self.live = self.by_hash.values().map(Vec::len).sum();
self.added = 0;
}
self.by_hash.entry(node.key.hash()).or_default().push(node);
}
}
pub trait Animated {
fn animated_node(&self) -> AnimatedNode;
}
#[derive(Clone)]
pub(crate) struct LiveNode(Rc<Node>);
impl LiveNode {
pub(crate) fn id(&self) -> crate::animation::NodeId {
self.0.id
}
fn act(&self, op: AnimationOp) {
self.0.act(op);
}
fn executor(&self) -> Option<Rc<Executor>> {
self.0.executor.upgrade()
}
}
impl PartialEq for LiveNode {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl fmt::Debug for LiveNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("LiveNode").field(&self.id()).finish()
}
}
#[derive(Clone, Copy)]
pub struct AnimatedNode {
node: Kept<Node>,
id: crate::animation::NodeId,
}
impl AnimatedNode {
fn keep(node: Rc<Node>) -> Self {
let id = node.id;
Self {
node: Kept::new(node),
id,
}
}
fn gone() -> Self {
Self {
node: Kept::gone(),
id: 0,
}
}
pub(crate) fn id(&self) -> crate::animation::NodeId {
self.id
}
pub(crate) fn live(&self) -> Option<LiveNode> {
self.node.get().map(LiveNode)
}
fn act(&self, op: impl FnOnce(crate::animation::NodeId) -> AnimationOp) {
let id = self.id;
self.node.with(|node| node.act(op(id)));
}
fn executor(&self) -> Option<Rc<Executor>> {
self.node.with(|node| node.executor.upgrade()).flatten()
}
fn derive(
&self,
key: DerivedKey,
now: Option<AnimationOp>,
others: &[Option<AnimatedNode>],
) -> (AnimatedNode, bool) {
let Some(node) = self.live() else {
return (Self::gone(), false);
};
let mut live = Vec::new();
for other in others.iter().flatten() {
match other.live() {
Some(other) => live.push(other),
None => return (Self::gone(), false),
}
}
let Some(executor) = node.executor() else {
return (*self, false);
};
let owner = Owner::current();
let mut derived = executor.derived();
if let Some(entry) = derived.entry(&key) {
entry.handles.retain(|(_, h)| h.node.is_live());
if let Some(&(_, handle)) = entry.handles.iter().find(|(o, _)| *o == owner) {
return (handle, false);
}
let Some(node) = entry.node.upgrade() else {
unreachable!("entries are of live nodes");
};
let handle = Self::keep(node);
entry.handles.push((owner, handle));
return (handle, true);
}
drop(derived);
let mut inputs = vec![node.0];
inputs.extend(live.into_iter().map(|o| o.0));
let op = now.unwrap_or_else(|| key.op.clone());
let node = Node::new(&executor, |id| with_node(op, id), inputs);
let weak = Rc::downgrade(&node);
let handle = Self::keep(node);
executor.derived().add(DerivedNode {
key,
node: weak,
handles: vec![(owner, handle)],
});
(handle, true)
}
pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
self.interpolate_with(
input,
Output::Numbers(output.to_vec()),
Interpolation::default(),
)
}
pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
&self,
input: &[f32],
colors: &[C],
) -> AnimatedNode {
let colors: Rc<[AdaptiveColor]> = colors.iter().map(|&c| c.into()).collect();
let pick = {
let colors = colors.clone();
move |dark: bool| {
Output::Colors(
colors
.iter()
.map(|c| crate::style::Color::from(if dark { c.dark } else { c.light }).0)
.collect(),
)
}
};
if colors.iter().all(|c| c.light == c.dark) {
return self.interpolate_with(input, pick(false), Interpolation::default());
}
let (node, new) = self.interpolate_derived(
input,
pick(false),
Some(pick(true)),
Interpolation::default(),
);
let Some(held) = node.live().filter(|_| new) else {
return node;
};
let first = Cell::new(true);
super::reactive::render_effect(move || {
let output = pick(super::dark());
if !first.replace(false) {
held.act(AnimationOp::SetOutput {
node: held.id(),
output,
});
}
});
node
}
pub fn interpolate_with(
&self,
input: &[f32],
output: Output,
interpolation: Interpolation,
) -> AnimatedNode {
self.interpolate_derived(input, output, None, interpolation)
.0
}
fn interpolate_derived(
&self,
input: &[f32],
output: Output,
dark: Option<Output>,
interpolation: Interpolation,
) -> (AnimatedNode, bool) {
let op = |output| AnimationOp::CreateInterpolate {
node: 0,
input: self.id(),
input_range: input.to_vec(),
output,
extrapolate_left: interpolation.extrapolate_left,
extrapolate_right: interpolation.extrapolate_right,
easing: interpolation.easing,
};
let now = dark
.clone()
.filter(|_| super::untracked(super::dark))
.map(op);
self.derive(
DerivedKey {
op: op(output),
dark,
},
now,
&[],
)
}
fn math(&self, op: MathOp, other: AnimationOperand) -> AnimatedNode {
let a = Operand::Node(self.id());
let b = other.operand;
let op = AnimationOp::CreateMath { node: 0, op, a, b };
self.derive(DerivedKey { op, dark: None }, None, &[other.node])
.0
}
pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.math(MathOp::Add, other.into())
}
pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.math(MathOp::Sub, other.into())
}
pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.math(MathOp::Mul, other.into())
}
pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.math(MathOp::Div, other.into())
}
pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.math(MathOp::Mod, other.into())
}
pub fn diff_clamp(
&self,
min: impl Into<AnimationOperand>,
max: impl Into<AnimationOperand>,
) -> AnimatedNode {
self.diff_clamp_with(min, max, DiffClamp::default())
}
pub fn diff_clamp_with(
&self,
min: impl Into<AnimationOperand>,
max: impl Into<AnimationOperand>,
options: DiffClamp,
) -> AnimatedNode {
let (min, max) = (min.into(), max.into());
let op = AnimationOp::CreateDiffClamp {
node: 0,
input: self.id(),
min: min.operand,
max: max.operand,
snap: options.snap,
};
self.derive(DerivedKey { op, dark: None }, None, &[min.node, max.node])
.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct DiffClamp {
pub snap: bool,
}
impl DiffClamp {
pub const fn snapping() -> Self {
Self { snap: true }
}
}
impl Animated for AnimatedNode {
fn animated_node(&self) -> AnimatedNode {
*self
}
}
impl PartialEq for AnimatedNode {
fn eq(&self, other: &Self) -> bool {
self.id() == other.id()
}
}
impl fmt::Debug for AnimatedNode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("AnimatedNode").field(&self.id()).finish()
}
}
#[derive(Debug, Clone)]
pub struct AnimationOperand {
operand: Operand,
node: Option<AnimatedNode>,
}
impl From<f32> for AnimationOperand {
fn from(n: f32) -> Self {
Self {
operand: Operand::Const(n),
node: None,
}
}
}
impl<A: Animated> From<&A> for AnimationOperand {
fn from(a: &A) -> Self {
let node = a.animated_node();
Self {
operand: Operand::Node(node.id()),
node: Some(node),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Interpolation {
pub extrapolate_left: Extrapolate,
pub extrapolate_right: Extrapolate,
pub easing: Easing,
}
impl Interpolation {
pub const fn extrapolate(extrapolate: Extrapolate) -> Self {
Self {
extrapolate_left: extrapolate,
extrapolate_right: extrapolate,
easing: Easing::Linear,
}
}
}
impl Default for Interpolation {
fn default() -> Self {
Self::extrapolate(Extrapolate::Clamp)
}
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct AnimatedValue(AnimatedNode);
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Spring {
pub stiffness: f32,
pub damping: f32,
pub mass: f32,
pub velocity: Option<f32>,
pub frame_rate: Option<f32>,
}
impl Default for Spring {
fn default() -> Self {
Self {
stiffness: 170.0,
damping: 26.0,
mass: 1.0,
velocity: None,
frame_rate: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Timing {
pub duration_ms: f32,
pub easing: Easing,
pub delay_ms: f32,
pub frame_rate: Option<f32>,
}
impl Timing {
pub const fn new(duration_ms: f32, easing: Easing) -> Self {
Self {
duration_ms,
easing,
delay_ms: 0.0,
frame_rate: None,
}
}
pub const fn frame_rate(mut self, hz: f32) -> Self {
self.frame_rate = Some(hz);
self
}
fn driver(self, to: f32) -> Driver {
Driver::Timing {
to,
duration_ms: self.duration_ms,
easing: self.easing,
delay_ms: self.delay_ms,
frame_rate: self.frame_rate,
}
}
}
impl Default for Timing {
fn default() -> Self {
Self::new(300.0, Easing::EaseInOut)
}
}
impl Spring {
pub fn new(response_ms: f32) -> Self {
let omega = std::f32::consts::TAU / (response_ms / 1000.0);
Self {
stiffness: omega * omega,
damping: 2.0 * omega,
mass: 1.0,
velocity: None,
frame_rate: None,
}
}
pub fn from_stiffness(stiffness: f32) -> Self {
Self {
stiffness,
damping: 2.0 * stiffness.max(0.0).sqrt(),
mass: 1.0,
velocity: None,
frame_rate: None,
}
}
pub fn damping_ratio(mut self, ratio: f32) -> Self {
self.damping = 2.0 * ratio * (self.stiffness * self.mass).max(0.0).sqrt();
self
}
pub fn progress(self, ms: f32) -> f32 {
let Some((zeta, omega)) = self.oscillator() else {
return 1.0;
};
if ms <= 0.0 {
return 0.0;
}
let t = ms / 1000.0;
if (zeta - 1.0).abs() < CRITICAL {
return 1.0 - (1.0 + omega * t) * (-omega * t).exp();
}
if zeta < 1.0 {
let decay = zeta * omega;
let wd = omega * (1.0 - zeta * zeta).sqrt();
return 1.0 - (-decay * t).exp() * ((wd * t).cos() + decay / wd * (wd * t).sin());
}
let root = omega * (zeta * zeta - 1.0).sqrt();
let (slow, fast) = (zeta * omega - root, zeta * omega + root);
1.0 - (fast * (-slow * t).exp() - slow * (-fast * t).exp()) / (fast - slow)
}
pub fn settle_ms(self) -> f32 {
let Some((zeta, omega)) = self.oscillator() else {
return 0.0;
};
let seconds = if (zeta - 1.0).abs() < CRITICAL {
9.233 / omega
} else if zeta < 1.0 {
SETTLE / (zeta * omega)
} else {
let root = (zeta * zeta - 1.0).sqrt();
let weight = (zeta + root) / (2.0 * root);
(SETTLE + weight.ln()) / (omega * (zeta - root))
};
seconds * 1000.0
}
fn oscillator(self) -> Option<(f32, f32)> {
let Spring {
stiffness,
damping,
mass,
..
} = self;
if !(stiffness > 0.0 && mass > 0.0 && damping > 0.0)
|| !(stiffness.is_finite() && mass.is_finite() && damping.is_finite())
{
return None;
}
let zeta = damping / (2.0 * (stiffness * mass).sqrt());
Some((zeta, (stiffness / mass).sqrt()))
}
pub const fn frame_rate(mut self, hz: f32) -> Self {
self.frame_rate = Some(hz);
self
}
fn driver(self, to: f32) -> Driver {
Driver::Spring {
to,
stiffness: self.stiffness,
damping: self.damping,
mass: self.mass,
velocity: self.velocity,
frame_rate: self.frame_rate,
}
}
}
const SETTLE: f32 = 6.907_755;
const CRITICAL: f32 = 1e-3;
fn sample(driver: Driver, from: f32, fps: f32) -> Vec<f32> {
let step = 1.0 / f64::from(fps.clamp(1.0, 1000.0));
crate::animation::sample_driver(driver, from, step, crate::animation::MAX_SAMPLES)
}
pub fn sample_spring(from: f32, to: f32, spring: Spring, fps: f32) -> Vec<f32> {
sample(spring.driver(to), from, fps)
}
pub fn sample_decay(from: f32, velocity: f32, deceleration: f32, fps: f32) -> Vec<f32> {
sample(
Driver::Decay {
velocity: Some(velocity),
deceleration,
clamp: None,
bounce: 0.0,
frame_rate: None,
},
from,
fps,
)
}
pub fn sample_decay_within(
from: f32,
velocity: f32,
deceleration: f32,
(min, max): (f32, f32),
bounce: f32,
fps: f32,
) -> Vec<f32> {
sample(
Driver::Decay {
velocity: Some(velocity),
deceleration,
clamp: Some((min, max)),
bounce,
frame_rate: None,
},
from,
fps,
)
}
#[derive(Debug)]
pub struct AnimationEnd(Answer<bool>);
impl std::future::IntoFuture for AnimationEnd {
type Output = bool;
type IntoFuture = Answer<bool>;
fn into_future(self) -> Answer<bool> {
self.0
}
}
impl AnimatedValue {
pub(crate) fn new(executor: &Rc<Executor>, value: f32) -> Self {
Self(AnimatedNode::keep(Node::new(
executor,
|node| AnimationOp::CreateValue { node, value },
Vec::new(),
)))
}
pub fn node(&self) -> &AnimatedNode {
&self.0
}
pub fn set(&self, value: f32) {
self.0.act(|node| AnimationOp::Set { node, value });
}
pub fn stop(&self) {
self.0.act(|node| AnimationOp::Stop { node });
}
pub fn value(&self) -> Answer<f32> {
let (answer, slot) = Answer::new();
if let Some(executor) = self.0.executor() {
executor.act(Action::ReadValue {
node: self.0.id(),
value: slot,
});
}
answer
}
fn start(&self, driver: Driver) -> AnimationEnd {
let (end, slot) = Answer::new();
let end = AnimationEnd(end);
match self.0.executor() {
Some(executor) => {
let animation = executor.next_animation_id();
executor.act(Action::Animate {
op: AnimationOp::Start {
node: self.0.id(),
animation,
driver,
},
animation,
end: slot,
});
}
None => slot.borrow_mut().deliver(false),
}
end
}
pub fn keyframes(
&self,
frames: impl IntoIterator<Item = Keyframe>,
timing: KeyframeTiming,
) -> AnimationEnd {
Animation::keyframes(self, frames, timing).start()
}
pub fn spring(&self, to: f32, spring: Spring) -> AnimationEnd {
self.start(spring.driver(to))
}
pub fn timing(&self, to: f32, ms: f32, easing: Easing) -> AnimationEnd {
self.timing_with(to, Timing::new(ms, easing))
}
pub fn timing_with(&self, to: f32, timing: Timing) -> AnimationEnd {
self.start(timing.driver(to))
}
pub fn decay(&self, velocity: Option<f32>, deceleration: f32) -> AnimationEnd {
self.start(Driver::Decay {
velocity,
deceleration,
clamp: None,
bounce: 0.0,
frame_rate: None,
})
}
pub fn decay_within(
&self,
velocity: Option<f32>,
deceleration: f32,
(min, max): (f32, f32),
bounce: f32,
) -> AnimationEnd {
self.start(Driver::Decay {
velocity,
deceleration,
clamp: Some((min, max)),
bounce,
frame_rate: None,
})
}
pub fn set_offset(&self, offset: f32) {
self.0.act(|node| AnimationOp::SetOffset { node, offset });
}
pub fn flatten_offset(&self) {
self.0.act(|node| AnimationOp::FlattenOffset { node });
}
pub fn extract_offset(&self) {
self.0.act(|node| AnimationOp::ExtractOffset { node });
}
pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
self.0.interpolate(input, output)
}
pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
&self,
input: &[f32],
colors: &[C],
) -> AnimatedNode {
self.0.interpolate_colors(input, colors)
}
pub fn interpolate_with(
&self,
input: &[f32],
output: Output,
interpolation: Interpolation,
) -> AnimatedNode {
self.0.interpolate_with(input, output, interpolation)
}
pub fn diff_clamp(
&self,
min: impl Into<AnimationOperand>,
max: impl Into<AnimationOperand>,
) -> AnimatedNode {
self.0.diff_clamp(min, max)
}
pub fn diff_clamp_with(
&self,
min: impl Into<AnimationOperand>,
max: impl Into<AnimationOperand>,
options: DiffClamp,
) -> AnimatedNode {
self.0.diff_clamp_with(min, max, options)
}
pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.0.add(other)
}
pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.0.sub(other)
}
pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.0.mul(other)
}
pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.0.div(other)
}
pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
self.0.modulo(other)
}
}
impl Animated for AnimatedValue {
fn animated_node(&self) -> AnimatedNode {
self.0
}
}
#[derive(Clone)]
pub struct Animation(Rc<Composed>);
struct Composed {
spec: Composite,
values: Vec<LiveNode>,
run: Run,
}
struct Run {
executor: Weak<Executor>,
key: Cell<u32>,
animation: Cell<AnimationId>,
}
impl Drop for Run {
fn drop(&mut self) {
let key = self.key.get();
if key != 0
&& let Some(executor) = self.executor.upgrade()
{
executor.act(Action::Animation(AnimationOp::ReleaseComposite { key }));
}
}
}
impl Animation {
fn new(spec: Composite, values: Vec<LiveNode>) -> Self {
let executor = values
.first()
.map(|n| n.0.executor.clone())
.unwrap_or_default();
Self(Rc::new(Composed {
spec,
values,
run: Run {
executor,
key: Cell::new(0),
animation: Cell::new(0),
},
}))
}
fn run(value: &AnimatedValue, driver: Driver) -> Self {
let node = value.0.id();
Self::new(
Composite::Run { node, driver },
value.0.live().into_iter().collect(),
)
}
pub fn timing(value: &AnimatedValue, to: f32, timing: Timing) -> Self {
Self::run(value, timing.driver(to))
}
pub fn spring(value: &AnimatedValue, to: f32, spring: Spring) -> Self {
Self::run(value, spring.driver(to))
}
pub fn decay(value: &AnimatedValue, velocity: Option<f32>, deceleration: f32) -> Self {
Self::run(
value,
Driver::Decay {
velocity,
deceleration,
clamp: None,
bounce: 0.0,
frame_rate: None,
},
)
}
pub fn decay_within(
value: &AnimatedValue,
velocity: Option<f32>,
deceleration: f32,
(min, max): (f32, f32),
bounce: f32,
) -> Self {
Self::run(
value,
Driver::Decay {
velocity,
deceleration,
clamp: Some((min, max)),
bounce,
frame_rate: None,
},
)
}
pub fn keyframes(
value: &AnimatedValue,
frames: impl IntoIterator<Item = Keyframe>,
timing: KeyframeTiming,
) -> Self {
let frames: Vec<Keyframe> = frames.into_iter().collect();
Self::new(
crate::animation::keyframes(value.0.id(), &frames, &timing),
value.0.live().into_iter().collect(),
)
}
pub fn delay(ms: f32) -> Self {
Self::new(Composite::Delay(ms), Vec::new())
}
fn into_parts(self) -> (Composite, Vec<LiveNode>) {
match Rc::try_unwrap(self.0) {
Ok(Composed { spec, values, .. }) => (spec, values),
Err(shared) => (shared.spec.clone(), shared.values.clone()),
}
}
fn group(
animations: impl IntoIterator<Item = Animation>,
make: impl FnOnce(Vec<Composite>) -> Composite,
) -> Self {
let mut specs = Vec::new();
let mut values: Vec<LiveNode> = Vec::new();
for animation in animations {
let (spec, of) = animation.into_parts();
specs.push(spec);
for value in of {
if !values.contains(&value) {
values.push(value);
}
}
}
Self::new(make(specs), values)
}
pub fn sequence(animations: impl IntoIterator<Item = Animation>) -> Self {
Self::group(animations, Composite::Sequence)
}
pub fn parallel(animations: impl IntoIterator<Item = Animation>) -> Self {
Self::group(animations, |children| Composite::Parallel {
children,
stop_together: true,
})
}
pub fn stagger(ms: f32, animations: impl IntoIterator<Item = Animation>) -> Self {
let staged = animations
.into_iter()
.enumerate()
.map(|(i, a)| Self::sequence([Self::delay(ms * i as f32), a]));
Self::parallel(staged)
}
pub fn stagger_from(
ms: f32,
from: StaggerFrom,
animations: impl IntoIterator<Item = Animation>,
) -> Self {
let animations: Vec<Animation> = animations.into_iter().collect();
let count = animations.len();
let staged = animations.into_iter().enumerate().map(|(i, a)| {
Self::sequence([
Self::delay(ms * crate::animation::stagger_delay(i, count, from)),
a,
])
});
Self::parallel(staged)
}
pub fn looped(self, iterations: Option<u32>) -> Self {
let (spec, values) = self.into_parts();
Self::new(
Composite::Loop {
child: Box::new(spec),
iterations,
reset: true,
},
values,
)
}
pub fn stop_together(self, stop_together: bool) -> Self {
let (mut spec, values) = self.into_parts();
if let Composite::Parallel {
stop_together: s, ..
} = &mut spec
{
*s = stop_together;
}
Self::new(spec, values)
}
pub fn reset_before_iteration(self, reset: bool) -> Self {
let (mut spec, values) = self.into_parts();
if let Composite::Loop { reset: r, .. } = &mut spec {
*r = reset;
}
Self::new(spec, values)
}
pub fn start(&self) -> AnimationEnd {
let (end, slot) = Answer::new();
let run = &self.0.run;
let Some(executor) = run.executor.upgrade() else {
if self.0.values.is_empty() {
slot.borrow_mut().deliver(true);
}
return AnimationEnd(end);
};
self.stop();
if run.key.get() == 0 {
run.key.set(executor.next_animation_id());
}
let animation = executor.next_animation_id();
run.animation.set(animation);
executor.act(Action::Animate {
op: AnimationOp::StartComposite {
animation,
key: run.key.get(),
spec: self.0.spec.clone(),
},
animation,
end: slot,
});
AnimationEnd(end)
}
pub fn stop(&self) {
let run = &self.0.run;
let animation = run.animation.replace(0);
if animation != 0
&& let Some(executor) = run.executor.upgrade()
{
executor.act(Action::Animation(AnimationOp::StopAnimation { animation }));
}
}
pub fn reset(&self) {
let run = &self.0.run;
run.animation.set(0);
let key = run.key.get();
if key != 0
&& let Some(executor) = run.executor.upgrade()
{
executor.act(Action::Animation(AnimationOp::ResetComposite { key }));
}
}
}
impl fmt::Debug for Animation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Animation").field(&self.0.spec).finish()
}
}
#[derive(Clone, Copy)]
pub struct Motion {
values: [AnimatedValue; 9],
}
impl fmt::Debug for Motion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Motion").finish_non_exhaustive()
}
}
impl Motion {
pub(crate) fn new(executor: &Rc<Executor>) -> Self {
Self {
values: MotionChannel::ALL.map(|c| AnimatedValue::new(executor, c.identity())),
}
}
pub fn value(&self, channel: MotionChannel) -> AnimatedValue {
self.values[channel.index()]
}
pub fn entering(self, motion: impl Into<MotionSpec>) -> Self {
let motion = motion.into();
for (channel, start) in motion.start_values() {
self.value(channel).set(start);
}
let _ = self.play(motion);
self
}
pub fn play(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
self.run(motion.into(), super::reduce_motion())
}
pub fn play_ignoring_reduce_motion(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
self.run(motion.into(), false)
}
pub fn animation(&self, motion: impl Into<MotionSpec>) -> Animation {
self.composed(motion.into(), super::reduce_motion())
}
fn composed(&self, motion: MotionSpec, reduced: bool) -> Animation {
let nodes = self.values.map(|v| v.0.id());
let held = self
.values
.iter()
.filter_map(|v| v.0.live())
.collect::<Vec<_>>();
Animation::new(motion.composite(&nodes, reduced), held)
}
fn run(&self, motion: MotionSpec, reduced: bool) -> AnimationEnd {
self.composed(motion, reduced).start()
}
pub fn stop(&self) {
for value in &self.values {
value.stop();
}
}
pub fn reset(&self) {
for channel in MotionChannel::ALL {
self.value(channel).set(channel.identity());
}
}
}
impl super::JsValue for Timing {
fn ts_type(_types: &mut super::TsTypes) -> String {
"{ duration?: number; easing?: import(\"nsh\").Easing; delay?: number; frameRate?: number }"
.into()
}
fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
let json = value.to_json()?;
let Some(object) = json.as_object() else {
return Err(value.expected("a timing: `{ duration, easing, delay }`"));
};
let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
let default = Timing::default();
Ok(Timing {
duration_ms: num("duration").unwrap_or(default.duration_ms).max(0.0),
easing: object
.get("easing")
.and_then(|e| crate::js::animation::easing(&JsonInput(Some(e))))
.unwrap_or(default.easing),
delay_ms: num("delay").unwrap_or(default.delay_ms).max(0.0),
frame_rate: crate::style::frame_rate(num("frameRate")),
})
}
fn to_js<'a>(
&self,
host: &'a dyn super::JsHost,
) -> Result<super::JsOwned<'a>, super::PropError> {
let mut json = serde_json::json!({ "duration": self.duration_ms, "delay": self.delay_ms });
if let Some(hz) = self.frame_rate {
json["frameRate"] = hz.into();
}
Ok(super::JsOwned::new(host, host.json(&json)?))
}
}
impl super::JsValue for Spring {
fn ts_type(_types: &mut super::TsTypes) -> String {
"{ stiffness?: number; damping?: number; mass?: number; velocity?: number; frameRate?: number }"
.into()
}
fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
let json = value.to_json()?;
let Some(object) = json.as_object() else {
return Err(value.expected("a spring: `{ stiffness, damping, mass }`"));
};
let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
let default = Spring::default();
Ok(Spring {
stiffness: num("stiffness").unwrap_or(default.stiffness),
damping: num("damping").unwrap_or(default.damping),
mass: num("mass").unwrap_or(default.mass),
velocity: num("velocity"),
frame_rate: crate::style::frame_rate(num("frameRate")),
})
}
fn to_js<'a>(
&self,
host: &'a dyn super::JsHost,
) -> Result<super::JsOwned<'a>, super::PropError> {
let mut json = serde_json::json!({
"stiffness": self.stiffness,
"damping": self.damping,
"mass": self.mass,
});
if let Some(hz) = self.frame_rate {
json["frameRate"] = hz.into();
}
Ok(super::JsOwned::new(host, host.json(&json)?))
}
}
pub(crate) struct JsonInput<'a>(pub(crate) Option<&'a crate::JsonValue>);
pub(crate) struct JsonList<'a>(&'a [crate::JsonValue]);
impl<'a> crate::js::host::HostList for JsonList<'a> {
type Item = JsonInput<'a>;
fn len(&self) -> usize {
self.0.len()
}
fn item(&self, index: usize) -> Option<JsonInput<'a>> {
self.0.get(index).map(|v| JsonInput(Some(v)))
}
}
impl<'a> crate::js::host::HostInput for JsonInput<'a> {
type List = JsonList<'a>;
fn is_nullish(&self) -> bool {
self.0.is_none_or(|v| v.is_null())
}
fn is_object(&self) -> bool {
self.0.is_some_and(|v| v.is_object() || v.is_array())
}
fn as_bool(&self) -> Option<bool> {
self.0?.as_bool()
}
fn as_number(&self) -> Option<f64> {
self.0?.as_f64()
}
fn as_string(&self) -> Option<String> {
self.0?.as_str().map(str::to_owned)
}
fn field(&self, key: &str) -> Option<Self> {
self.0?.get(key).map(|v| JsonInput(Some(v)))
}
fn as_list(&self) -> Option<JsonList<'a>> {
self.0?.as_array().map(|a| JsonList(a))
}
fn entries(&self) -> Vec<(String, Self)> {
match self.0.and_then(|v| v.as_object()) {
Some(o) => o
.iter()
.map(|(k, v)| (k.clone(), JsonInput(Some(v))))
.collect(),
None => Vec::new(),
}
}
fn truthy(&self) -> bool {
match self.0 {
None | Some(crate::JsonValue::Null) => false,
Some(crate::JsonValue::Bool(b)) => *b,
Some(crate::JsonValue::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),
Some(crate::JsonValue::String(s)) => !s.is_empty(),
Some(_) => true,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::element::reactive::{Runtime, create_root};
fn released(executor: &Executor) -> usize {
executor
.take_actions()
.into_iter()
.filter(|a| matches!(a, Action::Animation(AnimationOp::Release { .. })))
.count()
}
#[test]
fn a_derived_chain_keeps_its_middle_nodes() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let (value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.5));
let (chain_owner, end) = create_root(|| v.node().mul(2.0).sub(1.0));
let bound = end.live().expect("live");
chain_owner.dispose();
assert_eq!(released(&executor), 0, "the product lives with the end");
assert!(end.live().is_none(), "its handle is gone");
drop(bound);
assert_eq!(released(&executor), 2, "then both go");
value_owner.dispose();
assert_eq!(released(&executor), 1);
}
#[test]
fn copies_are_the_same_value_in_every_closure() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let (_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
let node = v.node().id();
let _ = ops(&executor);
let press = move || v.set(1.0);
let release = move || v.set_offset(2.0);
press();
release();
let _ = v.timing(3.0, 100.0, Easing::Linear);
assert!(matches!(
&ops(&executor)[..],
[
AnimationOp::Set { node: a, value: 1.0 },
AnimationOp::SetOffset { node: b, offset: 2.0 },
AnimationOp::Start { node: c, .. },
] if [*a, *b, *c] == [node; 3]
));
let copy = v;
assert_eq!(copy, v);
assert_eq!(
format!("{v:?}"),
format!("AnimatedValue(AnimatedNode({node}))")
);
}
#[test]
fn handles_do_nothing_once_their_owner_is_gone() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let (owner, (v, half)) = create_root(|| {
let v = AnimatedValue::new(&executor, 0.0);
(v, v.mul(0.5))
});
let jump = Animation::timing(&v, 1.0, Timing::default());
let _ = ops(&executor);
owner.dispose();
assert_eq!(ops(&executor), [AnimationOp::Release { node: half.id() }]);
drop(jump);
assert_eq!(
ops(&executor),
[AnimationOp::Release {
node: v.node().id()
}]
);
v.set(1.0);
v.stop();
v.set_offset(1.0);
v.flatten_offset();
v.extract_offset();
let ended = v.spring(1.0, Spring::default());
let tasks = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
assert!(!tasks.block_on(ended.into_future()), "unfinished, at once");
drop(v.value());
let derived = [
v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
v.add(&half),
half.mul(2.0),
];
assert!(derived.iter().all(|n| n.live().is_none()));
drop(Animation::timing(&v, 1.0, Timing::default()).start());
assert_eq!(ops(&executor), [], "nothing reaches the graph");
let copy = half;
assert_eq!(copy, half);
assert_eq!(format!("{half:?}"), format!("AnimatedNode({})", half.id()));
}
#[test]
fn deriving_again_finds_the_node_among_many() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let (_owner, (v, first, again, zeros)) = create_root(|| {
let v = AnimatedValue::new(&executor, 0.0);
let derive = || -> Vec<AnimatedNode> {
(0..2_000)
.map(|i| v.interpolate(&[0.0, 1.0], &[0.0, i as f32]))
.collect()
};
let first = derive();
let again = derive();
let zeros = [
v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
v.interpolate(&[-0.0, 1.0], &[-0.0, 1.0]),
];
(v, first, again, zeros)
});
assert!(first.iter().zip(&again).all(|(a, b)| a == b));
let mut ids: Vec<_> = first.iter().map(AnimatedNode::id).collect();
ids.dedup();
assert_eq!(ids.len(), 2_000, "distinct keys, distinct nodes");
assert_eq!(zeros[0], zeros[1]);
assert_eq!(zeros[0], first[1]);
let _ = v;
}
#[test]
fn dead_derived_nodes_are_neither_found_nor_kept() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let (_value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
let (owner, gone) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
let id = gone.id();
owner.dispose();
let (_owner, made) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
assert_ne!(made.id(), id, "a dead node is made again");
for round in 0..50 {
let (owner, _) = create_root(|| {
(0..200)
.map(|i| v.interpolate(&[0.0, 1.0], &[round as f32, i as f32]))
.collect::<Vec<_>>()
});
owner.dispose();
}
let kept: usize = executor.derived().by_hash.values().map(Vec::len).sum();
assert!(kept <= 2 * 200 + 64, "{kept} kept");
}
#[test]
#[ignore = "benchmark"]
fn bench_derive_many_nodes() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
for n in [5_000, 20_000] {
let start = std::time::Instant::now();
let (owner, _nodes) = create_root(|| {
let v = AnimatedValue::new(&executor, 0.0);
(0..n)
.map(|i| v.interpolate(&[0.0, 0.5, 1.0], &[0.0, i as f32, 1.0]))
.collect::<Vec<_>>()
});
println!("{n} derived nodes: {:?}", start.elapsed());
owner.dispose();
let _ = executor.take_actions();
}
}
fn ops(executor: &Executor) -> Vec<AnimationOp> {
executor
.take_actions()
.into_iter()
.filter_map(|a| match a {
Action::Animation(op) | Action::Animate { op, .. } => Some(op),
_ => None,
})
.collect()
}
fn timing(to: f32, ms: f32) -> Driver {
Timing::new(ms, Easing::Linear).driver(to)
}
#[test]
fn keyframes_staggers_and_motions_describe_their_trees() {
use crate::animation::{MotionPreset, StaggerFrom};
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let values: Vec<AnimatedValue> =
(0..3).map(|_| AnimatedValue::new(&executor, 0.0)).collect();
let step = |v: &AnimatedValue| {
Animation::keyframes(
v,
[Keyframe::new(0.0), Keyframe::new(1.0)],
KeyframeTiming::new(100.0),
)
};
let rippled = Animation::stagger_from(40.0, StaggerFrom::Center, values.iter().map(step));
let Composite::Parallel { children, .. } = &rippled.0.spec else {
panic!("{:?}", rippled.0.spec)
};
let delays: Vec<f32> = children
.iter()
.map(|c| match c {
Composite::Sequence(s) => match s[0] {
Composite::Delay(ms) => ms,
_ => -1.0,
},
_ => -1.0,
})
.collect();
assert_eq!(delays, [40.0, 0.0, 40.0]);
let motion = Motion::new(&executor);
executor.take_actions();
let _ = motion.play_ignoring_reduce_motion(MotionPreset::Shake);
let started = executor.take_actions().into_iter().find_map(|a| match a {
Action::Animate {
op: AnimationOp::StartComposite { spec, .. },
..
} => Some(spec),
_ => None,
});
let Some(Composite::Parallel { children, .. }) = started else {
panic!("{started:?}")
};
assert_eq!(children.len(), 1);
let mut nodes = Vec::new();
children[0].nodes(&mut nodes);
assert_eq!(nodes, [motion.value(MotionChannel::TranslateX).node().id()]);
}
#[test]
fn composites_describe_their_steps() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let (a, b) = (
AnimatedValue::new(&executor, 0.0),
AnimatedValue::new(&executor, 1.0),
);
let (na, nb) = (a.node().id(), b.node().id());
let run = |node, to| Composite::Run {
node,
driver: timing(to, 100.0),
};
let step =
|v: &AnimatedValue, to| Animation::timing(v, to, Timing::new(100.0, Easing::Linear));
let staggered = Animation::stagger(50.0, [step(&a, 1.0), step(&b, 2.0)]);
let delayed = |ms, c| Composite::Sequence(vec![Composite::Delay(ms), c]);
assert_eq!(
staggered.0.spec,
Composite::Parallel {
children: vec![delayed(0.0, run(na, 1.0)), delayed(50.0, run(nb, 2.0))],
stop_together: true,
}
);
let ids = |a: &Animation| a.0.values.iter().map(LiveNode::id).collect::<Vec<_>>();
assert_eq!(ids(&staggered), [na, nb]);
let looped = Animation::sequence([step(&a, 1.0), Animation::delay(10.0), step(&a, 0.0)])
.looped(Some(3))
.reset_before_iteration(false);
assert_eq!(
looped.0.spec,
Composite::Loop {
child: Box::new(Composite::Sequence(vec![
run(na, 1.0),
Composite::Delay(10.0),
run(na, 0.0)
])),
iterations: Some(3),
reset: false,
}
);
assert_eq!(ids(&looped), [na]);
let apart = Animation::parallel([step(&a, 1.0)]).stop_together(false);
assert!(matches!(
apart.0.spec,
Composite::Parallel {
stop_together: false,
..
}
));
let delayed = Animation::timing(
&a,
1.0,
Timing {
delay_ms: 40.0,
..Timing::default()
},
);
assert!(matches!(
delayed.0.spec,
Composite::Run {
driver: Driver::Timing {
delay_ms: 40.0,
duration_ms: 300.0,
easing: Easing::EaseInOut,
..
},
..
}
));
}
#[test]
fn composites_start_stop_reset_and_release_by_key() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let x = AnimatedValue::new(&executor, 0.0);
let _ = ops(&executor);
let jump = Animation::sequence([
Animation::timing(&x, 10.0, Timing::default()),
Animation::spring(&x, 0.0, Spring::default()),
]);
jump.stop();
jump.reset();
assert_eq!(ops(&executor), []);
let _ = jump.start();
let [
AnimationOp::StartComposite {
animation,
key,
spec,
},
] = &ops(&executor)[..]
else {
panic!("a composite start");
};
assert_eq!((animation % 2, key % 2), (1, 1), "the core's ids are odd");
assert_eq!(spec, &jump.0.spec);
let (first, key) = (*animation, *key);
let _ = jump.clone().start();
let again = ops(&executor);
assert!(matches!(
&again[..],
[
AnimationOp::StopAnimation { animation: a },
AnimationOp::StartComposite { animation: b, key: k, .. },
] if *a == first && *b != first && *k == key
));
jump.stop();
assert!(matches!(
&ops(&executor)[..],
[AnimationOp::StopAnimation { .. }]
));
jump.stop();
assert_eq!(ops(&executor), [], "stopped once");
jump.reset();
assert_eq!(ops(&executor), [AnimationOp::ResetComposite { key }]);
drop(jump);
assert_eq!(ops(&executor), [AnimationOp::ReleaseComposite { key }]);
}
#[test]
fn delays_alone_end_at_once() {
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.unwrap();
let end = Animation::sequence([Animation::delay(100.0)]).start();
assert!(runtime.block_on(end.into_future()));
}
#[test]
fn values_derive_like_their_nodes() {
let runtime = Runtime::default();
let _entered = runtime.enter();
let executor = Rc::new(Executor::default());
let t = AnimatedValue::new(&executor, 0.0);
let right = Interpolation {
extrapolate_right: Extrapolate::Extend,
..Interpolation::default()
};
let angle = t.interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right);
let [
..,
AnimationOp::CreateInterpolate {
extrapolate_left,
extrapolate_right,
easing,
..
},
] = &ops(&executor)[..]
else {
panic!("an interpolation");
};
assert_eq!(
(*extrapolate_left, *extrapolate_right, *easing),
(Extrapolate::Clamp, Extrapolate::Extend, Easing::Linear)
);
assert_eq!(
angle,
t.node()
.interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right)
);
assert_eq!(t.diff_clamp(0.0, 44.0), t.node().diff_clamp(0.0, 44.0));
assert_eq!(t.mul(-1.0), t.node().mul(-1.0));
}
#[test]
fn curves_sample_as_the_graph_runs_them() {
let spring = sample_spring(0.0, 1.0, Spring::default(), 60.0);
assert_eq!(spring[0], 0.0);
assert!((spring.last().unwrap() - 1.0).abs() < 1e-3, "{spring:?}");
let fast = sample_spring(0.0, 1.0, Spring::default(), 120.0);
assert!(fast.len() > spring.len() * 3 / 2, "{}", fast.len());
let undamped = Spring {
damping: 0.0,
..Spring::default()
};
assert_eq!(
sample_spring(0.0, 1.0, undamped, 60.0).len(),
crate::animation::MAX_SAMPLES
);
let decay = sample_decay(0.0, 1000.0, 0.998, 60.0);
assert!(decay.windows(2).all(|w| w[1] >= w[0]), "{decay:?}");
assert!(*decay.last().unwrap() > 400.0, "{decay:?}");
let within = sample_decay_within(0.0, 1000.0, 0.998, (0.0, 100.0), 0.0, 60.0);
assert!(within.iter().all(|&x| (0.0..=100.0).contains(&x)));
assert_eq!(*within.last().unwrap(), 100.0);
let curve = super::super::sample_easing(Easing::EaseInOut, 5);
assert_eq!((curve[0], curve[4], curve.len()), (0.0, 1.0, 5));
}
}