1use std::{
27 cell::Cell,
28 fmt,
29 rc::{Rc, Weak},
30};
31
32use super::{
33 AdaptiveColor,
34 reactive::{Kept, Owner},
35 task::{Action, Answer, Executor},
36};
37use crate::animation::{
38 AnimationId, AnimationOp, Composite, Driver, Easing, Extrapolate, Keyframe, KeyframeTiming,
39 MathOp, MotionChannel, MotionSpec, Operand, Output, StaggerFrom,
40};
41
42pub(crate) struct Node {
45 id: crate::animation::NodeId,
46 executor: Weak<Executor>,
47 _inputs: Vec<Rc<Node>>,
50}
51
52impl Node {
53 fn new(
54 executor: &Rc<Executor>,
55 op: impl FnOnce(crate::animation::NodeId) -> AnimationOp,
56 inputs: Vec<Rc<Node>>,
57 ) -> Rc<Self> {
58 let id = executor.next_animation_id();
59 executor.act(Action::Animation(op(id)));
60 Rc::new(Self {
61 id,
62 executor: Rc::downgrade(executor),
63 _inputs: inputs,
64 })
65 }
66
67 fn act(&self, op: AnimationOp) {
68 if let Some(executor) = self.executor.upgrade() {
69 executor.act(Action::Animation(op));
70 }
71 }
72}
73
74impl Drop for Node {
75 fn drop(&mut self) {
76 self.act(AnimationOp::Release { node: self.id });
77 }
78}
79
80fn with_node(mut op: AnimationOp, id: crate::animation::NodeId) -> AnimationOp {
82 match &mut op {
83 AnimationOp::CreateValue { node, .. }
84 | AnimationOp::CreateInterpolate { node, .. }
85 | AnimationOp::CreateDiffClamp { node, .. }
86 | AnimationOp::CreateMath { node, .. } => *node = id,
87 _ => {}
88 }
89 op
90}
91
92#[derive(Default)]
101pub(crate) struct Derived {
102 by_hash: rustc_hash::FxHashMap<u64, Vec<DerivedNode>>,
103 added: usize,
105 live: usize,
107}
108
109#[derive(Clone, PartialEq)]
115struct DerivedKey {
116 op: AnimationOp,
117 dark: Option<Output>,
118}
119
120struct DerivedNode {
121 key: DerivedKey,
122 node: Weak<Node>,
123 handles: Vec<(Owner, AnimatedNode)>,
125}
126
127impl DerivedKey {
128 fn hash(&self) -> u64 {
131 use std::hash::{Hash, Hasher};
132 fn number(h: &mut rustc_hash::FxHasher, v: f32) {
133 (if v == 0.0 { 0 } else { v.to_bits() }).hash(h);
134 }
135 fn operand(h: &mut rustc_hash::FxHasher, o: &Operand) {
136 match *o {
137 Operand::Node(n) => n.hash(h),
138 Operand::Const(c) => number(h, c),
139 }
140 }
141 let mut h = rustc_hash::FxHasher::default();
142 std::mem::discriminant(&self.op).hash(&mut h);
143 match &self.op {
144 AnimationOp::CreateInterpolate {
145 input,
146 input_range,
147 output,
148 ..
149 } => {
150 input.hash(&mut h);
151 input_range.iter().for_each(|&v| number(&mut h, v));
152 match output {
153 Output::Numbers(v) => v.iter().for_each(|&v| number(&mut h, v)),
154 Output::Colors(v) => v.hash(&mut h),
155 }
156 }
157 AnimationOp::CreateMath { a, b, .. } => {
158 operand(&mut h, a);
159 operand(&mut h, b);
160 }
161 AnimationOp::CreateDiffClamp {
162 input, min, max, ..
163 } => {
164 input.hash(&mut h);
165 operand(&mut h, min);
166 operand(&mut h, max);
167 }
168 _ => {}
169 }
170 h.finish()
171 }
172}
173
174impl Derived {
175 fn entry(&mut self, key: &DerivedKey) -> Option<&mut DerivedNode> {
177 let same = self.by_hash.get_mut(&key.hash())?;
178 same.retain(|d| d.node.strong_count() > 0);
179 same.iter_mut().find(|d| d.key == *key)
180 }
181
182 fn add(&mut self, node: DerivedNode) {
186 self.added += 1;
187 if self.added > self.live.max(64) {
188 self.by_hash.retain(|_, same| {
189 same.retain(|d| d.node.strong_count() > 0);
190 !same.is_empty()
191 });
192 self.live = self.by_hash.values().map(Vec::len).sum();
193 self.added = 0;
194 }
195 self.by_hash.entry(node.key.hash()).or_default().push(node);
196 }
197}
198
199pub trait Animated {
202 fn animated_node(&self) -> AnimatedNode;
204}
205
206#[derive(Clone)]
210pub(crate) struct LiveNode(Rc<Node>);
211
212impl LiveNode {
213 pub(crate) fn id(&self) -> crate::animation::NodeId {
214 self.0.id
215 }
216
217 fn act(&self, op: AnimationOp) {
218 self.0.act(op);
219 }
220
221 fn executor(&self) -> Option<Rc<Executor>> {
222 self.0.executor.upgrade()
223 }
224}
225
226impl PartialEq for LiveNode {
227 fn eq(&self, other: &Self) -> bool {
228 self.id() == other.id()
229 }
230}
231
232impl fmt::Debug for LiveNode {
233 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
234 f.debug_tuple("LiveNode").field(&self.id()).finish()
235 }
236}
237
238#[derive(Clone, Copy)]
242pub struct AnimatedNode {
243 node: Kept<Node>,
244 id: crate::animation::NodeId,
247}
248
249impl AnimatedNode {
250 fn keep(node: Rc<Node>) -> Self {
252 let id = node.id;
253 Self {
254 node: Kept::new(node),
255 id,
256 }
257 }
258
259 fn gone() -> Self {
261 Self {
262 node: Kept::gone(),
263 id: 0,
264 }
265 }
266
267 pub(crate) fn id(&self) -> crate::animation::NodeId {
268 self.id
269 }
270
271 pub(crate) fn live(&self) -> Option<LiveNode> {
274 self.node.get().map(LiveNode)
275 }
276
277 fn act(&self, op: impl FnOnce(crate::animation::NodeId) -> AnimationOp) {
280 let id = self.id;
281 self.node.with(|node| node.act(op(id)));
282 }
283
284 fn executor(&self) -> Option<Rc<Executor>> {
286 self.node.with(|node| node.executor.upgrade()).flatten()
287 }
288
289 fn derive(
298 &self,
299 key: DerivedKey,
300 now: Option<AnimationOp>,
301 others: &[Option<AnimatedNode>],
302 ) -> (AnimatedNode, bool) {
303 let Some(node) = self.live() else {
304 return (Self::gone(), false);
305 };
306 let mut live = Vec::new();
307 for other in others.iter().flatten() {
308 match other.live() {
309 Some(other) => live.push(other),
310 None => return (Self::gone(), false),
311 }
312 }
313 let Some(executor) = node.executor() else {
314 return (*self, false);
316 };
317 let owner = Owner::current();
318 let mut derived = executor.derived();
319 if let Some(entry) = derived.entry(&key) {
320 entry.handles.retain(|(_, h)| h.node.is_live());
321 if let Some(&(_, handle)) = entry.handles.iter().find(|(o, _)| *o == owner) {
322 return (handle, false);
323 }
324 let Some(node) = entry.node.upgrade() else {
325 unreachable!("entries are of live nodes");
326 };
327 let handle = Self::keep(node);
328 entry.handles.push((owner, handle));
329 return (handle, true);
330 }
331 drop(derived);
332 let mut inputs = vec![node.0];
333 inputs.extend(live.into_iter().map(|o| o.0));
334 let op = now.unwrap_or_else(|| key.op.clone());
335 let node = Node::new(&executor, |id| with_node(op, id), inputs);
336 let weak = Rc::downgrade(&node);
337 let handle = Self::keep(node);
338 executor.derived().add(DerivedNode {
339 key,
340 node: weak,
341 handles: vec![(owner, handle)],
342 });
343 (handle, true)
344 }
345
346 pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
349 self.interpolate_with(
350 input,
351 Output::Numbers(output.to_vec()),
352 Interpolation::default(),
353 )
354 }
355
356 pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
361 &self,
362 input: &[f32],
363 colors: &[C],
364 ) -> AnimatedNode {
365 let colors: Rc<[AdaptiveColor]> = colors.iter().map(|&c| c.into()).collect();
366 let pick = {
367 let colors = colors.clone();
368 move |dark: bool| {
369 Output::Colors(
370 colors
371 .iter()
372 .map(|c| crate::style::Color::from(if dark { c.dark } else { c.light }).0)
373 .collect(),
374 )
375 }
376 };
377 if colors.iter().all(|c| c.light == c.dark) {
378 return self.interpolate_with(input, pick(false), Interpolation::default());
379 }
380 let (node, new) = self.interpolate_derived(
381 input,
382 pick(false),
383 Some(pick(true)),
384 Interpolation::default(),
385 );
386 let Some(held) = node.live().filter(|_| new) else {
390 return node;
391 };
392 let first = Cell::new(true);
393 super::reactive::render_effect(move || {
394 let output = pick(super::dark());
395 if !first.replace(false) {
396 held.act(AnimationOp::SetOutput {
397 node: held.id(),
398 output,
399 });
400 }
401 });
402 node
403 }
404
405 pub fn interpolate_with(
409 &self,
410 input: &[f32],
411 output: Output,
412 interpolation: Interpolation,
413 ) -> AnimatedNode {
414 self.interpolate_derived(input, output, None, interpolation)
415 .0
416 }
417
418 fn interpolate_derived(
422 &self,
423 input: &[f32],
424 output: Output,
425 dark: Option<Output>,
426 interpolation: Interpolation,
427 ) -> (AnimatedNode, bool) {
428 let op = |output| AnimationOp::CreateInterpolate {
429 node: 0,
430 input: self.id(),
431 input_range: input.to_vec(),
432 output,
433 extrapolate_left: interpolation.extrapolate_left,
434 extrapolate_right: interpolation.extrapolate_right,
435 easing: interpolation.easing,
436 };
437 let now = dark
438 .clone()
439 .filter(|_| super::untracked(super::dark))
440 .map(op);
441 self.derive(
442 DerivedKey {
443 op: op(output),
444 dark,
445 },
446 now,
447 &[],
448 )
449 }
450
451 fn math(&self, op: MathOp, other: AnimationOperand) -> AnimatedNode {
452 let a = Operand::Node(self.id());
453 let b = other.operand;
454 let op = AnimationOp::CreateMath { node: 0, op, a, b };
455 self.derive(DerivedKey { op, dark: None }, None, &[other.node])
456 .0
457 }
458
459 pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
461 self.math(MathOp::Add, other.into())
462 }
463
464 pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
466 self.math(MathOp::Sub, other.into())
467 }
468
469 pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
471 self.math(MathOp::Mul, other.into())
472 }
473
474 pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
476 self.math(MathOp::Div, other.into())
477 }
478
479 pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
481 self.math(MathOp::Mod, other.into())
482 }
483
484 pub fn diff_clamp(
489 &self,
490 min: impl Into<AnimationOperand>,
491 max: impl Into<AnimationOperand>,
492 ) -> AnimatedNode {
493 self.diff_clamp_with(min, max, DiffClamp::default())
494 }
495
496 pub fn diff_clamp_with(
500 &self,
501 min: impl Into<AnimationOperand>,
502 max: impl Into<AnimationOperand>,
503 options: DiffClamp,
504 ) -> AnimatedNode {
505 let (min, max) = (min.into(), max.into());
506 let op = AnimationOp::CreateDiffClamp {
507 node: 0,
508 input: self.id(),
509 min: min.operand,
510 max: max.operand,
511 snap: options.snap,
512 };
513 self.derive(DerivedKey { op, dark: None }, None, &[min.node, max.node])
514 .0
515 }
516}
517
518#[derive(Debug, Clone, Copy, PartialEq, Default)]
521#[non_exhaustive]
522pub struct DiffClamp {
523 pub snap: bool,
529}
530
531impl DiffClamp {
532 pub const fn snapping() -> Self {
534 Self { snap: true }
535 }
536}
537
538impl Animated for AnimatedNode {
539 fn animated_node(&self) -> AnimatedNode {
540 *self
541 }
542}
543
544impl PartialEq for AnimatedNode {
545 fn eq(&self, other: &Self) -> bool {
546 self.id() == other.id()
547 }
548}
549
550impl fmt::Debug for AnimatedNode {
551 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552 f.debug_tuple("AnimatedNode").field(&self.id()).finish()
553 }
554}
555
556#[derive(Debug, Clone)]
558pub struct AnimationOperand {
559 operand: Operand,
560 node: Option<AnimatedNode>,
562}
563
564impl From<f32> for AnimationOperand {
565 fn from(n: f32) -> Self {
566 Self {
567 operand: Operand::Const(n),
568 node: None,
569 }
570 }
571}
572
573impl<A: Animated> From<&A> for AnimationOperand {
574 fn from(a: &A) -> Self {
575 let node = a.animated_node();
576 Self {
577 operand: Operand::Node(node.id()),
578 node: Some(node),
579 }
580 }
581}
582
583#[derive(Debug, Clone, Copy, PartialEq)]
588pub struct Interpolation {
589 pub extrapolate_left: Extrapolate,
591 pub extrapolate_right: Extrapolate,
593 pub easing: Easing,
595}
596
597impl Interpolation {
598 pub const fn extrapolate(extrapolate: Extrapolate) -> Self {
600 Self {
601 extrapolate_left: extrapolate,
602 extrapolate_right: extrapolate,
603 easing: Easing::Linear,
604 }
605 }
606}
607
608impl Default for Interpolation {
609 fn default() -> Self {
610 Self::extrapolate(Extrapolate::Clamp)
611 }
612}
613
614#[derive(Clone, Copy, PartialEq, Debug)]
620pub struct AnimatedValue(AnimatedNode);
621
622#[derive(Debug, Clone, Copy, PartialEq)]
642pub struct Spring {
643 pub stiffness: f32,
645 pub damping: f32,
648 pub mass: f32,
650 pub velocity: Option<f32>,
653 pub frame_rate: Option<f32>,
656}
657
658impl Default for Spring {
659 fn default() -> Self {
660 Self {
661 stiffness: 170.0,
662 damping: 26.0,
663 mass: 1.0,
664 velocity: None,
665 frame_rate: None,
666 }
667 }
668}
669
670#[derive(Debug, Clone, Copy, PartialEq)]
673pub struct Timing {
674 pub duration_ms: f32,
676 pub easing: Easing,
678 pub delay_ms: f32,
680 pub frame_rate: Option<f32>,
683}
684
685impl Timing {
686 pub const fn new(duration_ms: f32, easing: Easing) -> Self {
688 Self {
689 duration_ms,
690 easing,
691 delay_ms: 0.0,
692 frame_rate: None,
693 }
694 }
695
696 pub const fn frame_rate(mut self, hz: f32) -> Self {
698 self.frame_rate = Some(hz);
699 self
700 }
701
702 fn driver(self, to: f32) -> Driver {
703 Driver::Timing {
704 to,
705 duration_ms: self.duration_ms,
706 easing: self.easing,
707 delay_ms: self.delay_ms,
708 frame_rate: self.frame_rate,
709 }
710 }
711}
712
713impl Default for Timing {
714 fn default() -> Self {
715 Self::new(300.0, Easing::EaseInOut)
716 }
717}
718
719impl Spring {
720 pub fn new(response_ms: f32) -> Self {
725 let omega = std::f32::consts::TAU / (response_ms / 1000.0);
726 Self {
727 stiffness: omega * omega,
728 damping: 2.0 * omega,
729 mass: 1.0,
730 velocity: None,
731 frame_rate: None,
732 }
733 }
734
735 pub fn from_stiffness(stiffness: f32) -> Self {
739 Self {
740 stiffness,
741 damping: 2.0 * stiffness.max(0.0).sqrt(),
742 mass: 1.0,
743 velocity: None,
744 frame_rate: None,
745 }
746 }
747
748 pub fn damping_ratio(mut self, ratio: f32) -> Self {
753 self.damping = 2.0 * ratio * (self.stiffness * self.mass).max(0.0).sqrt();
754 self
755 }
756
757 pub fn progress(self, ms: f32) -> f32 {
762 let Some((zeta, omega)) = self.oscillator() else {
763 return 1.0;
764 };
765 if ms <= 0.0 {
766 return 0.0;
767 }
768 let t = ms / 1000.0;
769 if (zeta - 1.0).abs() < CRITICAL {
770 return 1.0 - (1.0 + omega * t) * (-omega * t).exp();
771 }
772 if zeta < 1.0 {
773 let decay = zeta * omega;
774 let wd = omega * (1.0 - zeta * zeta).sqrt();
775 return 1.0 - (-decay * t).exp() * ((wd * t).cos() + decay / wd * (wd * t).sin());
776 }
777 let root = omega * (zeta * zeta - 1.0).sqrt();
778 let (slow, fast) = (zeta * omega - root, zeta * omega + root);
779 1.0 - (fast * (-slow * t).exp() - slow * (-fast * t).exp()) / (fast - slow)
780 }
781
782 pub fn settle_ms(self) -> f32 {
786 let Some((zeta, omega)) = self.oscillator() else {
787 return 0.0;
788 };
789 let seconds = if (zeta - 1.0).abs() < CRITICAL {
790 9.233 / omega
792 } else if zeta < 1.0 {
793 SETTLE / (zeta * omega)
794 } else {
795 let root = (zeta * zeta - 1.0).sqrt();
797 let weight = (zeta + root) / (2.0 * root);
798 (SETTLE + weight.ln()) / (omega * (zeta - root))
799 };
800 seconds * 1000.0
801 }
802
803 fn oscillator(self) -> Option<(f32, f32)> {
806 let Spring {
807 stiffness,
808 damping,
809 mass,
810 ..
811 } = self;
812 if !(stiffness > 0.0 && mass > 0.0 && damping > 0.0)
813 || !(stiffness.is_finite() && mass.is_finite() && damping.is_finite())
814 {
815 return None;
816 }
817 let zeta = damping / (2.0 * (stiffness * mass).sqrt());
818 Some((zeta, (stiffness / mass).sqrt()))
819 }
820
821 pub const fn frame_rate(mut self, hz: f32) -> Self {
823 self.frame_rate = Some(hz);
824 self
825 }
826
827 fn driver(self, to: f32) -> Driver {
828 Driver::Spring {
829 to,
830 stiffness: self.stiffness,
831 damping: self.damping,
832 mass: self.mass,
833 velocity: self.velocity,
834 frame_rate: self.frame_rate,
835 }
836 }
837}
838
839const SETTLE: f32 = 6.907_755;
841
842const CRITICAL: f32 = 1e-3;
845
846fn sample(driver: Driver, from: f32, fps: f32) -> Vec<f32> {
849 let step = 1.0 / f64::from(fps.clamp(1.0, 1000.0));
850 crate::animation::sample_driver(driver, from, step, crate::animation::MAX_SAMPLES)
851}
852
853pub fn sample_spring(from: f32, to: f32, spring: Spring, fps: f32) -> Vec<f32> {
858 sample(spring.driver(to), from, fps)
859}
860
861pub fn sample_decay(from: f32, velocity: f32, deceleration: f32, fps: f32) -> Vec<f32> {
866 sample(
867 Driver::Decay {
868 velocity: Some(velocity),
869 deceleration,
870 clamp: None,
871 bounce: 0.0,
872 frame_rate: None,
873 },
874 from,
875 fps,
876 )
877}
878
879pub fn sample_decay_within(
882 from: f32,
883 velocity: f32,
884 deceleration: f32,
885 (min, max): (f32, f32),
886 bounce: f32,
887 fps: f32,
888) -> Vec<f32> {
889 sample(
890 Driver::Decay {
891 velocity: Some(velocity),
892 deceleration,
893 clamp: Some((min, max)),
894 bounce,
895 frame_rate: None,
896 },
897 from,
898 fps,
899 )
900}
901
902#[derive(Debug)]
907pub struct AnimationEnd(Answer<bool>);
908
909impl std::future::IntoFuture for AnimationEnd {
910 type Output = bool;
911 type IntoFuture = Answer<bool>;
912
913 fn into_future(self) -> Answer<bool> {
914 self.0
915 }
916}
917
918impl AnimatedValue {
919 pub(crate) fn new(executor: &Rc<Executor>, value: f32) -> Self {
920 Self(AnimatedNode::keep(Node::new(
921 executor,
922 |node| AnimationOp::CreateValue { node, value },
923 Vec::new(),
924 )))
925 }
926
927 pub fn node(&self) -> &AnimatedNode {
929 &self.0
930 }
931
932 pub fn set(&self, value: f32) {
934 self.0.act(|node| AnimationOp::Set { node, value });
935 }
936
937 pub fn stop(&self) {
940 self.0.act(|node| AnimationOp::Stop { node });
941 }
942
943 pub fn value(&self) -> Answer<f32> {
948 let (answer, slot) = Answer::new();
949 if let Some(executor) = self.0.executor() {
950 executor.act(Action::ReadValue {
951 node: self.0.id(),
952 value: slot,
953 });
954 }
955 answer
956 }
957
958 fn start(&self, driver: Driver) -> AnimationEnd {
959 let (end, slot) = Answer::new();
960 let end = AnimationEnd(end);
961 match self.0.executor() {
962 Some(executor) => {
963 let animation = executor.next_animation_id();
964 executor.act(Action::Animate {
965 op: AnimationOp::Start {
966 node: self.0.id(),
967 animation,
968 driver,
969 },
970 animation,
971 end: slot,
972 });
973 }
974 None => slot.borrow_mut().deliver(false),
976 }
977 end
978 }
979
980 pub fn keyframes(
984 &self,
985 frames: impl IntoIterator<Item = Keyframe>,
986 timing: KeyframeTiming,
987 ) -> AnimationEnd {
988 Animation::keyframes(self, frames, timing).start()
989 }
990
991 pub fn spring(&self, to: f32, spring: Spring) -> AnimationEnd {
993 self.start(spring.driver(to))
994 }
995
996 pub fn timing(&self, to: f32, ms: f32, easing: Easing) -> AnimationEnd {
998 self.timing_with(to, Timing::new(ms, easing))
999 }
1000
1001 pub fn timing_with(&self, to: f32, timing: Timing) -> AnimationEnd {
1003 self.start(timing.driver(to))
1004 }
1005
1006 pub fn decay(&self, velocity: Option<f32>, deceleration: f32) -> AnimationEnd {
1009 self.start(Driver::Decay {
1010 velocity,
1011 deceleration,
1012 clamp: None,
1013 bounce: 0.0,
1014 frame_rate: None,
1015 })
1016 }
1017
1018 pub fn decay_within(
1021 &self,
1022 velocity: Option<f32>,
1023 deceleration: f32,
1024 (min, max): (f32, f32),
1025 bounce: f32,
1026 ) -> AnimationEnd {
1027 self.start(Driver::Decay {
1028 velocity,
1029 deceleration,
1030 clamp: Some((min, max)),
1031 bounce,
1032 frame_rate: None,
1033 })
1034 }
1035
1036 pub fn set_offset(&self, offset: f32) {
1039 self.0.act(|node| AnimationOp::SetOffset { node, offset });
1040 }
1041
1042 pub fn flatten_offset(&self) {
1044 self.0.act(|node| AnimationOp::FlattenOffset { node });
1045 }
1046
1047 pub fn extract_offset(&self) {
1050 self.0.act(|node| AnimationOp::ExtractOffset { node });
1051 }
1052
1053 pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
1055 self.0.interpolate(input, output)
1056 }
1057
1058 pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
1060 &self,
1061 input: &[f32],
1062 colors: &[C],
1063 ) -> AnimatedNode {
1064 self.0.interpolate_colors(input, colors)
1065 }
1066
1067 pub fn interpolate_with(
1069 &self,
1070 input: &[f32],
1071 output: Output,
1072 interpolation: Interpolation,
1073 ) -> AnimatedNode {
1074 self.0.interpolate_with(input, output, interpolation)
1075 }
1076
1077 pub fn diff_clamp(
1079 &self,
1080 min: impl Into<AnimationOperand>,
1081 max: impl Into<AnimationOperand>,
1082 ) -> AnimatedNode {
1083 self.0.diff_clamp(min, max)
1084 }
1085
1086 pub fn diff_clamp_with(
1088 &self,
1089 min: impl Into<AnimationOperand>,
1090 max: impl Into<AnimationOperand>,
1091 options: DiffClamp,
1092 ) -> AnimatedNode {
1093 self.0.diff_clamp_with(min, max, options)
1094 }
1095
1096 pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1098 self.0.add(other)
1099 }
1100
1101 pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1103 self.0.sub(other)
1104 }
1105
1106 pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1108 self.0.mul(other)
1109 }
1110
1111 pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1113 self.0.div(other)
1114 }
1115
1116 pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
1118 self.0.modulo(other)
1119 }
1120}
1121
1122impl Animated for AnimatedValue {
1123 fn animated_node(&self) -> AnimatedNode {
1124 self.0
1125 }
1126}
1127
1128#[derive(Clone)]
1153pub struct Animation(Rc<Composed>);
1154
1155struct Composed {
1156 spec: Composite,
1157 values: Vec<LiveNode>,
1159 run: Run,
1160}
1161
1162struct Run {
1164 executor: Weak<Executor>,
1165 key: Cell<u32>,
1167 animation: Cell<AnimationId>,
1169}
1170
1171impl Drop for Run {
1172 fn drop(&mut self) {
1173 let key = self.key.get();
1175 if key != 0
1176 && let Some(executor) = self.executor.upgrade()
1177 {
1178 executor.act(Action::Animation(AnimationOp::ReleaseComposite { key }));
1179 }
1180 }
1181}
1182
1183impl Animation {
1184 fn new(spec: Composite, values: Vec<LiveNode>) -> Self {
1185 let executor = values
1186 .first()
1187 .map(|n| n.0.executor.clone())
1188 .unwrap_or_default();
1189 Self(Rc::new(Composed {
1190 spec,
1191 values,
1192 run: Run {
1193 executor,
1194 key: Cell::new(0),
1195 animation: Cell::new(0),
1196 },
1197 }))
1198 }
1199
1200 fn run(value: &AnimatedValue, driver: Driver) -> Self {
1201 let node = value.0.id();
1202 Self::new(
1203 Composite::Run { node, driver },
1204 value.0.live().into_iter().collect(),
1205 )
1206 }
1207
1208 pub fn timing(value: &AnimatedValue, to: f32, timing: Timing) -> Self {
1210 Self::run(value, timing.driver(to))
1211 }
1212
1213 pub fn spring(value: &AnimatedValue, to: f32, spring: Spring) -> Self {
1215 Self::run(value, spring.driver(to))
1216 }
1217
1218 pub fn decay(value: &AnimatedValue, velocity: Option<f32>, deceleration: f32) -> Self {
1222 Self::run(
1223 value,
1224 Driver::Decay {
1225 velocity,
1226 deceleration,
1227 clamp: None,
1228 bounce: 0.0,
1229 frame_rate: None,
1230 },
1231 )
1232 }
1233
1234 pub fn decay_within(
1237 value: &AnimatedValue,
1238 velocity: Option<f32>,
1239 deceleration: f32,
1240 (min, max): (f32, f32),
1241 bounce: f32,
1242 ) -> Self {
1243 Self::run(
1244 value,
1245 Driver::Decay {
1246 velocity,
1247 deceleration,
1248 clamp: Some((min, max)),
1249 bounce,
1250 frame_rate: None,
1251 },
1252 )
1253 }
1254
1255 pub fn keyframes(
1260 value: &AnimatedValue,
1261 frames: impl IntoIterator<Item = Keyframe>,
1262 timing: KeyframeTiming,
1263 ) -> Self {
1264 let frames: Vec<Keyframe> = frames.into_iter().collect();
1265 Self::new(
1266 crate::animation::keyframes(value.0.id(), &frames, &timing),
1267 value.0.live().into_iter().collect(),
1268 )
1269 }
1270
1271 pub fn delay(ms: f32) -> Self {
1273 Self::new(Composite::Delay(ms), Vec::new())
1274 }
1275
1276 fn into_parts(self) -> (Composite, Vec<LiveNode>) {
1278 match Rc::try_unwrap(self.0) {
1279 Ok(Composed { spec, values, .. }) => (spec, values),
1280 Err(shared) => (shared.spec.clone(), shared.values.clone()),
1281 }
1282 }
1283
1284 fn group(
1285 animations: impl IntoIterator<Item = Animation>,
1286 make: impl FnOnce(Vec<Composite>) -> Composite,
1287 ) -> Self {
1288 let mut specs = Vec::new();
1289 let mut values: Vec<LiveNode> = Vec::new();
1290 for animation in animations {
1291 let (spec, of) = animation.into_parts();
1292 specs.push(spec);
1293 for value in of {
1294 if !values.contains(&value) {
1295 values.push(value);
1296 }
1297 }
1298 }
1299 Self::new(make(specs), values)
1300 }
1301
1302 pub fn sequence(animations: impl IntoIterator<Item = Animation>) -> Self {
1305 Self::group(animations, Composite::Sequence)
1306 }
1307
1308 pub fn parallel(animations: impl IntoIterator<Item = Animation>) -> Self {
1311 Self::group(animations, |children| Composite::Parallel {
1312 children,
1313 stop_together: true,
1314 })
1315 }
1316
1317 pub fn stagger(ms: f32, animations: impl IntoIterator<Item = Animation>) -> Self {
1320 let staged = animations
1321 .into_iter()
1322 .enumerate()
1323 .map(|(i, a)| Self::sequence([Self::delay(ms * i as f32), a]));
1324 Self::parallel(staged)
1325 }
1326
1327 pub fn stagger_from(
1331 ms: f32,
1332 from: StaggerFrom,
1333 animations: impl IntoIterator<Item = Animation>,
1334 ) -> Self {
1335 let animations: Vec<Animation> = animations.into_iter().collect();
1336 let count = animations.len();
1337 let staged = animations.into_iter().enumerate().map(|(i, a)| {
1338 Self::sequence([
1339 Self::delay(ms * crate::animation::stagger_delay(i, count, from)),
1340 a,
1341 ])
1342 });
1343 Self::parallel(staged)
1344 }
1345
1346 pub fn looped(self, iterations: Option<u32>) -> Self {
1350 let (spec, values) = self.into_parts();
1351 Self::new(
1352 Composite::Loop {
1353 child: Box::new(spec),
1354 iterations,
1355 reset: true,
1356 },
1357 values,
1358 )
1359 }
1360
1361 pub fn stop_together(self, stop_together: bool) -> Self {
1365 let (mut spec, values) = self.into_parts();
1366 if let Composite::Parallel {
1367 stop_together: s, ..
1368 } = &mut spec
1369 {
1370 *s = stop_together;
1371 }
1372 Self::new(spec, values)
1373 }
1374
1375 pub fn reset_before_iteration(self, reset: bool) -> Self {
1379 let (mut spec, values) = self.into_parts();
1380 if let Composite::Loop { reset: r, .. } = &mut spec {
1381 *r = reset;
1382 }
1383 Self::new(spec, values)
1384 }
1385
1386 pub fn start(&self) -> AnimationEnd {
1391 let (end, slot) = Answer::new();
1392 let run = &self.0.run;
1393 let Some(executor) = run.executor.upgrade() else {
1394 if self.0.values.is_empty() {
1395 slot.borrow_mut().deliver(true);
1396 }
1397 return AnimationEnd(end);
1398 };
1399 self.stop();
1400 if run.key.get() == 0 {
1401 run.key.set(executor.next_animation_id());
1402 }
1403 let animation = executor.next_animation_id();
1404 run.animation.set(animation);
1405 executor.act(Action::Animate {
1406 op: AnimationOp::StartComposite {
1407 animation,
1408 key: run.key.get(),
1409 spec: self.0.spec.clone(),
1410 },
1411 animation,
1412 end: slot,
1413 });
1414 AnimationEnd(end)
1415 }
1416
1417 pub fn stop(&self) {
1419 let run = &self.0.run;
1420 let animation = run.animation.replace(0);
1421 if animation != 0
1422 && let Some(executor) = run.executor.upgrade()
1423 {
1424 executor.act(Action::Animation(AnimationOp::StopAnimation { animation }));
1425 }
1426 }
1427
1428 pub fn reset(&self) {
1431 let run = &self.0.run;
1432 run.animation.set(0);
1433 let key = run.key.get();
1434 if key != 0
1435 && let Some(executor) = run.executor.upgrade()
1436 {
1437 executor.act(Action::Animation(AnimationOp::ResetComposite { key }));
1438 }
1439 }
1440}
1441
1442impl fmt::Debug for Animation {
1443 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1444 f.debug_tuple("Animation").field(&self.0.spec).finish()
1445 }
1446}
1447
1448#[derive(Clone, Copy)]
1462pub struct Motion {
1463 values: [AnimatedValue; 9],
1464}
1465
1466impl fmt::Debug for Motion {
1467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1468 f.debug_struct("Motion").finish_non_exhaustive()
1469 }
1470}
1471
1472impl Motion {
1473 pub(crate) fn new(executor: &Rc<Executor>) -> Self {
1474 Self {
1475 values: MotionChannel::ALL.map(|c| AnimatedValue::new(executor, c.identity())),
1476 }
1477 }
1478
1479 pub fn value(&self, channel: MotionChannel) -> AnimatedValue {
1482 self.values[channel.index()]
1483 }
1484
1485 pub fn entering(self, motion: impl Into<MotionSpec>) -> Self {
1488 let motion = motion.into();
1489 for (channel, start) in motion.start_values() {
1490 self.value(channel).set(start);
1491 }
1492 let _ = self.play(motion);
1493 self
1494 }
1495
1496 pub fn play(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
1500 self.run(motion.into(), super::reduce_motion())
1501 }
1502
1503 pub fn play_ignoring_reduce_motion(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
1505 self.run(motion.into(), false)
1506 }
1507
1508 pub fn animation(&self, motion: impl Into<MotionSpec>) -> Animation {
1514 self.composed(motion.into(), super::reduce_motion())
1515 }
1516
1517 fn composed(&self, motion: MotionSpec, reduced: bool) -> Animation {
1518 let nodes = self.values.map(|v| v.0.id());
1519 let held = self
1520 .values
1521 .iter()
1522 .filter_map(|v| v.0.live())
1523 .collect::<Vec<_>>();
1524 Animation::new(motion.composite(&nodes, reduced), held)
1525 }
1526
1527 fn run(&self, motion: MotionSpec, reduced: bool) -> AnimationEnd {
1528 self.composed(motion, reduced).start()
1529 }
1530
1531 pub fn stop(&self) {
1533 for value in &self.values {
1534 value.stop();
1535 }
1536 }
1537
1538 pub fn reset(&self) {
1540 for channel in MotionChannel::ALL {
1541 self.value(channel).set(channel.identity());
1542 }
1543 }
1544}
1545
1546impl super::JsValue for Timing {
1551 fn ts_type(_types: &mut super::TsTypes) -> String {
1552 "{ duration?: number; easing?: import(\"nsh\").Easing; delay?: number; frameRate?: number }"
1553 .into()
1554 }
1555
1556 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
1557 let json = value.to_json()?;
1558 let Some(object) = json.as_object() else {
1559 return Err(value.expected("a timing: `{ duration, easing, delay }`"));
1560 };
1561 let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
1562 let default = Timing::default();
1563 Ok(Timing {
1564 duration_ms: num("duration").unwrap_or(default.duration_ms).max(0.0),
1565 easing: object
1566 .get("easing")
1567 .and_then(|e| crate::js::animation::easing(&JsonInput(Some(e))))
1568 .unwrap_or(default.easing),
1569 delay_ms: num("delay").unwrap_or(default.delay_ms).max(0.0),
1570 frame_rate: crate::style::frame_rate(num("frameRate")),
1571 })
1572 }
1573
1574 fn to_js<'a>(
1575 &self,
1576 host: &'a dyn super::JsHost,
1577 ) -> Result<super::JsOwned<'a>, super::PropError> {
1578 let mut json = serde_json::json!({ "duration": self.duration_ms, "delay": self.delay_ms });
1579 if let Some(hz) = self.frame_rate {
1580 json["frameRate"] = hz.into();
1581 }
1582 Ok(super::JsOwned::new(host, host.json(&json)?))
1583 }
1584}
1585
1586impl super::JsValue for Spring {
1590 fn ts_type(_types: &mut super::TsTypes) -> String {
1591 "{ stiffness?: number; damping?: number; mass?: number; velocity?: number; frameRate?: number }"
1592 .into()
1593 }
1594
1595 fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
1596 let json = value.to_json()?;
1597 let Some(object) = json.as_object() else {
1598 return Err(value.expected("a spring: `{ stiffness, damping, mass }`"));
1599 };
1600 let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
1601 let default = Spring::default();
1602 Ok(Spring {
1603 stiffness: num("stiffness").unwrap_or(default.stiffness),
1604 damping: num("damping").unwrap_or(default.damping),
1605 mass: num("mass").unwrap_or(default.mass),
1606 velocity: num("velocity"),
1607 frame_rate: crate::style::frame_rate(num("frameRate")),
1608 })
1609 }
1610
1611 fn to_js<'a>(
1612 &self,
1613 host: &'a dyn super::JsHost,
1614 ) -> Result<super::JsOwned<'a>, super::PropError> {
1615 let mut json = serde_json::json!({
1616 "stiffness": self.stiffness,
1617 "damping": self.damping,
1618 "mass": self.mass,
1619 });
1620 if let Some(hz) = self.frame_rate {
1621 json["frameRate"] = hz.into();
1622 }
1623 Ok(super::JsOwned::new(host, host.json(&json)?))
1624 }
1625}
1626
1627pub(crate) struct JsonInput<'a>(pub(crate) Option<&'a crate::JsonValue>);
1630
1631pub(crate) struct JsonList<'a>(&'a [crate::JsonValue]);
1633
1634impl<'a> crate::js::host::HostList for JsonList<'a> {
1635 type Item = JsonInput<'a>;
1636
1637 fn len(&self) -> usize {
1638 self.0.len()
1639 }
1640
1641 fn item(&self, index: usize) -> Option<JsonInput<'a>> {
1642 self.0.get(index).map(|v| JsonInput(Some(v)))
1643 }
1644}
1645
1646impl<'a> crate::js::host::HostInput for JsonInput<'a> {
1647 type List = JsonList<'a>;
1648
1649 fn is_nullish(&self) -> bool {
1650 self.0.is_none_or(|v| v.is_null())
1651 }
1652
1653 fn is_object(&self) -> bool {
1654 self.0.is_some_and(|v| v.is_object() || v.is_array())
1655 }
1656
1657 fn as_bool(&self) -> Option<bool> {
1658 self.0?.as_bool()
1659 }
1660
1661 fn as_number(&self) -> Option<f64> {
1662 self.0?.as_f64()
1663 }
1664
1665 fn as_string(&self) -> Option<String> {
1666 self.0?.as_str().map(str::to_owned)
1667 }
1668
1669 fn field(&self, key: &str) -> Option<Self> {
1670 self.0?.get(key).map(|v| JsonInput(Some(v)))
1671 }
1672
1673 fn as_list(&self) -> Option<JsonList<'a>> {
1674 self.0?.as_array().map(|a| JsonList(a))
1675 }
1676
1677 fn entries(&self) -> Vec<(String, Self)> {
1678 match self.0.and_then(|v| v.as_object()) {
1679 Some(o) => o
1680 .iter()
1681 .map(|(k, v)| (k.clone(), JsonInput(Some(v))))
1682 .collect(),
1683 None => Vec::new(),
1684 }
1685 }
1686
1687 fn truthy(&self) -> bool {
1688 match self.0 {
1689 None | Some(crate::JsonValue::Null) => false,
1690 Some(crate::JsonValue::Bool(b)) => *b,
1691 Some(crate::JsonValue::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),
1692 Some(crate::JsonValue::String(s)) => !s.is_empty(),
1693 Some(_) => true,
1694 }
1695 }
1696}
1697
1698#[cfg(test)]
1699mod tests {
1700 use super::*;
1701 use crate::element::reactive::{Runtime, create_root};
1702
1703 fn released(executor: &Executor) -> usize {
1704 executor
1705 .take_actions()
1706 .into_iter()
1707 .filter(|a| matches!(a, Action::Animation(AnimationOp::Release { .. })))
1708 .count()
1709 }
1710
1711 #[test]
1712 fn a_derived_chain_keeps_its_middle_nodes() {
1713 let runtime = Runtime::default();
1714 let _entered = runtime.enter();
1715 let executor = Rc::new(Executor::default());
1716 let (value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.5));
1717 let (chain_owner, end) = create_root(|| v.node().mul(2.0).sub(1.0));
1720 let bound = end.live().expect("live");
1721 chain_owner.dispose();
1722 assert_eq!(released(&executor), 0, "the product lives with the end");
1723 assert!(end.live().is_none(), "its handle is gone");
1724 drop(bound);
1725 assert_eq!(released(&executor), 2, "then both go");
1726 value_owner.dispose();
1727 assert_eq!(released(&executor), 1);
1728 }
1729
1730 #[test]
1731 fn copies_are_the_same_value_in_every_closure() {
1732 let runtime = Runtime::default();
1733 let _entered = runtime.enter();
1734 let executor = Rc::new(Executor::default());
1735 let (_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
1736 let node = v.node().id();
1737 let _ = ops(&executor);
1738 let press = move || v.set(1.0);
1740 let release = move || v.set_offset(2.0);
1741 press();
1742 release();
1743 let _ = v.timing(3.0, 100.0, Easing::Linear);
1744 assert!(matches!(
1745 &ops(&executor)[..],
1746 [
1747 AnimationOp::Set { node: a, value: 1.0 },
1748 AnimationOp::SetOffset { node: b, offset: 2.0 },
1749 AnimationOp::Start { node: c, .. },
1750 ] if [*a, *b, *c] == [node; 3]
1751 ));
1752 let copy = v;
1753 assert_eq!(copy, v);
1754 assert_eq!(
1755 format!("{v:?}"),
1756 format!("AnimatedValue(AnimatedNode({node}))")
1757 );
1758 }
1759
1760 #[test]
1761 fn handles_do_nothing_once_their_owner_is_gone() {
1762 let runtime = Runtime::default();
1763 let _entered = runtime.enter();
1764 let executor = Rc::new(Executor::default());
1765 let (owner, (v, half)) = create_root(|| {
1766 let v = AnimatedValue::new(&executor, 0.0);
1767 (v, v.mul(0.5))
1768 });
1769 let jump = Animation::timing(&v, 1.0, Timing::default());
1770 let _ = ops(&executor);
1771 owner.dispose();
1772 assert_eq!(ops(&executor), [AnimationOp::Release { node: half.id() }]);
1775 drop(jump);
1776 assert_eq!(
1777 ops(&executor),
1778 [AnimationOp::Release {
1779 node: v.node().id()
1780 }]
1781 );
1782
1783 v.set(1.0);
1784 v.stop();
1785 v.set_offset(1.0);
1786 v.flatten_offset();
1787 v.extract_offset();
1788 let ended = v.spring(1.0, Spring::default());
1789 let tasks = tokio::runtime::Builder::new_current_thread()
1790 .build()
1791 .unwrap();
1792 assert!(!tasks.block_on(ended.into_future()), "unfinished, at once");
1793 drop(v.value());
1794 let derived = [
1795 v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
1796 v.add(&half),
1797 half.mul(2.0),
1798 ];
1799 assert!(derived.iter().all(|n| n.live().is_none()));
1800 drop(Animation::timing(&v, 1.0, Timing::default()).start());
1801 assert_eq!(ops(&executor), [], "nothing reaches the graph");
1802 let copy = half;
1804 assert_eq!(copy, half);
1805 assert_eq!(format!("{half:?}"), format!("AnimatedNode({})", half.id()));
1806 }
1807
1808 #[test]
1809 fn deriving_again_finds_the_node_among_many() {
1810 let runtime = Runtime::default();
1811 let _entered = runtime.enter();
1812 let executor = Rc::new(Executor::default());
1813 let (_owner, (v, first, again, zeros)) = create_root(|| {
1814 let v = AnimatedValue::new(&executor, 0.0);
1815 let derive = || -> Vec<AnimatedNode> {
1816 (0..2_000)
1817 .map(|i| v.interpolate(&[0.0, 1.0], &[0.0, i as f32]))
1818 .collect()
1819 };
1820 let first = derive();
1821 let again = derive();
1822 let zeros = [
1824 v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
1825 v.interpolate(&[-0.0, 1.0], &[-0.0, 1.0]),
1826 ];
1827 (v, first, again, zeros)
1828 });
1829 assert!(first.iter().zip(&again).all(|(a, b)| a == b));
1830 let mut ids: Vec<_> = first.iter().map(AnimatedNode::id).collect();
1831 ids.dedup();
1832 assert_eq!(ids.len(), 2_000, "distinct keys, distinct nodes");
1833 assert_eq!(zeros[0], zeros[1]);
1834 assert_eq!(zeros[0], first[1]);
1835 let _ = v;
1836 }
1837
1838 #[test]
1839 fn dead_derived_nodes_are_neither_found_nor_kept() {
1840 let runtime = Runtime::default();
1841 let _entered = runtime.enter();
1842 let executor = Rc::new(Executor::default());
1843 let (_value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
1844 let (owner, gone) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
1845 let id = gone.id();
1846 owner.dispose();
1847 let (_owner, made) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
1848 assert_ne!(made.id(), id, "a dead node is made again");
1849 for round in 0..50 {
1851 let (owner, _) = create_root(|| {
1852 (0..200)
1853 .map(|i| v.interpolate(&[0.0, 1.0], &[round as f32, i as f32]))
1854 .collect::<Vec<_>>()
1855 });
1856 owner.dispose();
1857 }
1858 let kept: usize = executor.derived().by_hash.values().map(Vec::len).sum();
1859 assert!(kept <= 2 * 200 + 64, "{kept} kept");
1860 }
1861
1862 #[test]
1866 #[ignore = "benchmark"]
1867 fn bench_derive_many_nodes() {
1868 let runtime = Runtime::default();
1869 let _entered = runtime.enter();
1870 let executor = Rc::new(Executor::default());
1871 for n in [5_000, 20_000] {
1872 let start = std::time::Instant::now();
1873 let (owner, _nodes) = create_root(|| {
1874 let v = AnimatedValue::new(&executor, 0.0);
1875 (0..n)
1876 .map(|i| v.interpolate(&[0.0, 0.5, 1.0], &[0.0, i as f32, 1.0]))
1877 .collect::<Vec<_>>()
1878 });
1879 println!("{n} derived nodes: {:?}", start.elapsed());
1880 owner.dispose();
1881 let _ = executor.take_actions();
1882 }
1883 }
1884
1885 fn ops(executor: &Executor) -> Vec<AnimationOp> {
1888 executor
1889 .take_actions()
1890 .into_iter()
1891 .filter_map(|a| match a {
1892 Action::Animation(op) | Action::Animate { op, .. } => Some(op),
1893 _ => None,
1894 })
1895 .collect()
1896 }
1897
1898 fn timing(to: f32, ms: f32) -> Driver {
1899 Timing::new(ms, Easing::Linear).driver(to)
1900 }
1901
1902 #[test]
1903 fn keyframes_staggers_and_motions_describe_their_trees() {
1904 use crate::animation::{MotionPreset, StaggerFrom};
1905 let runtime = Runtime::default();
1906 let _entered = runtime.enter();
1907 let executor = Rc::new(Executor::default());
1908 let values: Vec<AnimatedValue> =
1909 (0..3).map(|_| AnimatedValue::new(&executor, 0.0)).collect();
1910 let step = |v: &AnimatedValue| {
1911 Animation::keyframes(
1912 v,
1913 [Keyframe::new(0.0), Keyframe::new(1.0)],
1914 KeyframeTiming::new(100.0),
1915 )
1916 };
1917 let rippled = Animation::stagger_from(40.0, StaggerFrom::Center, values.iter().map(step));
1918 let Composite::Parallel { children, .. } = &rippled.0.spec else {
1919 panic!("{:?}", rippled.0.spec)
1920 };
1921 let delays: Vec<f32> = children
1922 .iter()
1923 .map(|c| match c {
1924 Composite::Sequence(s) => match s[0] {
1925 Composite::Delay(ms) => ms,
1926 _ => -1.0,
1927 },
1928 _ => -1.0,
1929 })
1930 .collect();
1931 assert_eq!(delays, [40.0, 0.0, 40.0]);
1932
1933 let motion = Motion::new(&executor);
1934 executor.take_actions();
1935 let _ = motion.play_ignoring_reduce_motion(MotionPreset::Shake);
1936 let started = executor.take_actions().into_iter().find_map(|a| match a {
1937 Action::Animate {
1938 op: AnimationOp::StartComposite { spec, .. },
1939 ..
1940 } => Some(spec),
1941 _ => None,
1942 });
1943 let Some(Composite::Parallel { children, .. }) = started else {
1944 panic!("{started:?}")
1945 };
1946 assert_eq!(children.len(), 1);
1948 let mut nodes = Vec::new();
1949 children[0].nodes(&mut nodes);
1950 assert_eq!(nodes, [motion.value(MotionChannel::TranslateX).node().id()]);
1951 }
1952
1953 #[test]
1954 fn composites_describe_their_steps() {
1955 let runtime = Runtime::default();
1956 let _entered = runtime.enter();
1957 let executor = Rc::new(Executor::default());
1958 let (a, b) = (
1959 AnimatedValue::new(&executor, 0.0),
1960 AnimatedValue::new(&executor, 1.0),
1961 );
1962 let (na, nb) = (a.node().id(), b.node().id());
1963 let run = |node, to| Composite::Run {
1964 node,
1965 driver: timing(to, 100.0),
1966 };
1967 let step =
1968 |v: &AnimatedValue, to| Animation::timing(v, to, Timing::new(100.0, Easing::Linear));
1969 let staggered = Animation::stagger(50.0, [step(&a, 1.0), step(&b, 2.0)]);
1970 let delayed = |ms, c| Composite::Sequence(vec![Composite::Delay(ms), c]);
1971 assert_eq!(
1972 staggered.0.spec,
1973 Composite::Parallel {
1974 children: vec![delayed(0.0, run(na, 1.0)), delayed(50.0, run(nb, 2.0))],
1975 stop_together: true,
1976 }
1977 );
1978 let ids = |a: &Animation| a.0.values.iter().map(LiveNode::id).collect::<Vec<_>>();
1979 assert_eq!(ids(&staggered), [na, nb]);
1980
1981 let looped = Animation::sequence([step(&a, 1.0), Animation::delay(10.0), step(&a, 0.0)])
1982 .looped(Some(3))
1983 .reset_before_iteration(false);
1984 assert_eq!(
1985 looped.0.spec,
1986 Composite::Loop {
1987 child: Box::new(Composite::Sequence(vec![
1988 run(na, 1.0),
1989 Composite::Delay(10.0),
1990 run(na, 0.0)
1991 ])),
1992 iterations: Some(3),
1993 reset: false,
1994 }
1995 );
1996 assert_eq!(ids(&looped), [na]);
1998 let apart = Animation::parallel([step(&a, 1.0)]).stop_together(false);
1999 assert!(matches!(
2000 apart.0.spec,
2001 Composite::Parallel {
2002 stop_together: false,
2003 ..
2004 }
2005 ));
2006 let delayed = Animation::timing(
2008 &a,
2009 1.0,
2010 Timing {
2011 delay_ms: 40.0,
2012 ..Timing::default()
2013 },
2014 );
2015 assert!(matches!(
2016 delayed.0.spec,
2017 Composite::Run {
2018 driver: Driver::Timing {
2019 delay_ms: 40.0,
2020 duration_ms: 300.0,
2021 easing: Easing::EaseInOut,
2022 ..
2023 },
2024 ..
2025 }
2026 ));
2027 }
2028
2029 #[test]
2030 fn composites_start_stop_reset_and_release_by_key() {
2031 let runtime = Runtime::default();
2032 let _entered = runtime.enter();
2033 let executor = Rc::new(Executor::default());
2034 let x = AnimatedValue::new(&executor, 0.0);
2035 let _ = ops(&executor);
2036 let jump = Animation::sequence([
2037 Animation::timing(&x, 10.0, Timing::default()),
2038 Animation::spring(&x, 0.0, Spring::default()),
2039 ]);
2040 jump.stop();
2042 jump.reset();
2043 assert_eq!(ops(&executor), []);
2044
2045 let _ = jump.start();
2046 let [
2047 AnimationOp::StartComposite {
2048 animation,
2049 key,
2050 spec,
2051 },
2052 ] = &ops(&executor)[..]
2053 else {
2054 panic!("a composite start");
2055 };
2056 assert_eq!((animation % 2, key % 2), (1, 1), "the core's ids are odd");
2057 assert_eq!(spec, &jump.0.spec);
2058 let (first, key) = (*animation, *key);
2059
2060 let _ = jump.clone().start();
2062 let again = ops(&executor);
2063 assert!(matches!(
2064 &again[..],
2065 [
2066 AnimationOp::StopAnimation { animation: a },
2067 AnimationOp::StartComposite { animation: b, key: k, .. },
2068 ] if *a == first && *b != first && *k == key
2069 ));
2070 jump.stop();
2071 assert!(matches!(
2072 &ops(&executor)[..],
2073 [AnimationOp::StopAnimation { .. }]
2074 ));
2075 jump.stop();
2076 assert_eq!(ops(&executor), [], "stopped once");
2077 jump.reset();
2078 assert_eq!(ops(&executor), [AnimationOp::ResetComposite { key }]);
2079
2080 drop(jump);
2081 assert_eq!(ops(&executor), [AnimationOp::ReleaseComposite { key }]);
2082 }
2083
2084 #[test]
2085 fn delays_alone_end_at_once() {
2086 let runtime = tokio::runtime::Builder::new_current_thread()
2087 .build()
2088 .unwrap();
2089 let end = Animation::sequence([Animation::delay(100.0)]).start();
2090 assert!(runtime.block_on(end.into_future()));
2091 }
2092
2093 #[test]
2094 fn values_derive_like_their_nodes() {
2095 let runtime = Runtime::default();
2096 let _entered = runtime.enter();
2097 let executor = Rc::new(Executor::default());
2098 let t = AnimatedValue::new(&executor, 0.0);
2099 let right = Interpolation {
2100 extrapolate_right: Extrapolate::Extend,
2101 ..Interpolation::default()
2102 };
2103 let angle = t.interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right);
2104 let [
2105 ..,
2106 AnimationOp::CreateInterpolate {
2107 extrapolate_left,
2108 extrapolate_right,
2109 easing,
2110 ..
2111 },
2112 ] = &ops(&executor)[..]
2113 else {
2114 panic!("an interpolation");
2115 };
2116 assert_eq!(
2117 (*extrapolate_left, *extrapolate_right, *easing),
2118 (Extrapolate::Clamp, Extrapolate::Extend, Easing::Linear)
2119 );
2120 assert_eq!(
2122 angle,
2123 t.node()
2124 .interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right)
2125 );
2126 assert_eq!(t.diff_clamp(0.0, 44.0), t.node().diff_clamp(0.0, 44.0));
2127 assert_eq!(t.mul(-1.0), t.node().mul(-1.0));
2128 }
2129
2130 #[test]
2131 fn curves_sample_as_the_graph_runs_them() {
2132 let spring = sample_spring(0.0, 1.0, Spring::default(), 60.0);
2135 assert_eq!(spring[0], 0.0);
2136 assert!((spring.last().unwrap() - 1.0).abs() < 1e-3, "{spring:?}");
2137 let fast = sample_spring(0.0, 1.0, Spring::default(), 120.0);
2138 assert!(fast.len() > spring.len() * 3 / 2, "{}", fast.len());
2139 let undamped = Spring {
2141 damping: 0.0,
2142 ..Spring::default()
2143 };
2144 assert_eq!(
2145 sample_spring(0.0, 1.0, undamped, 60.0).len(),
2146 crate::animation::MAX_SAMPLES
2147 );
2148 let decay = sample_decay(0.0, 1000.0, 0.998, 60.0);
2150 assert!(decay.windows(2).all(|w| w[1] >= w[0]), "{decay:?}");
2151 assert!(*decay.last().unwrap() > 400.0, "{decay:?}");
2152 let within = sample_decay_within(0.0, 1000.0, 0.998, (0.0, 100.0), 0.0, 60.0);
2153 assert!(within.iter().all(|&x| (0.0..=100.0).contains(&x)));
2154 assert_eq!(*within.last().unwrap(), 100.0);
2155 let curve = super::super::sample_easing(Easing::EaseInOut, 5);
2157 assert_eq!((curve[0], curve[4], curve.len()), (0.0, 1.0, 5));
2158 }
2159}