1use super::ops::{Composite, Driver, Easing, NodeId};
18use crate::{TransformKind, element::Spring};
19
20#[derive(Debug, Clone, Copy, PartialEq)]
23#[non_exhaustive]
24pub struct Keyframe {
25 pub offset: Option<f32>,
28 pub value: f32,
30 pub easing: Option<Easing>,
32}
33
34impl Default for Keyframe {
35 fn default() -> Self {
36 Self {
37 offset: None,
38 value: 0.0,
39 easing: None,
40 }
41 }
42}
43
44impl Keyframe {
45 pub const fn new(value: f32) -> Self {
47 Self {
48 offset: None,
49 value,
50 easing: None,
51 }
52 }
53
54 pub const fn at(offset: f32, value: f32) -> Self {
56 Self {
57 offset: Some(offset),
58 value,
59 easing: None,
60 }
61 }
62
63 pub const fn ease(mut self, easing: Easing) -> Self {
65 self.easing = Some(easing);
66 self
67 }
68}
69
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
72pub enum PlaybackDirection {
73 #[default]
75 Normal,
76 Reverse,
78 Alternate,
80 AlternateReverse,
82}
83
84impl PlaybackDirection {
85 pub fn parse(name: &str) -> Option<PlaybackDirection> {
87 Some(match name {
88 "normal" => PlaybackDirection::Normal,
89 "reverse" => PlaybackDirection::Reverse,
90 "alternate" => PlaybackDirection::Alternate,
91 "alternate-reverse" => PlaybackDirection::AlternateReverse,
92 _ => return None,
93 })
94 }
95
96 pub fn name(self) -> &'static str {
98 match self {
99 PlaybackDirection::Normal => "normal",
100 PlaybackDirection::Reverse => "reverse",
101 PlaybackDirection::Alternate => "alternate",
102 PlaybackDirection::AlternateReverse => "alternate-reverse",
103 }
104 }
105
106 fn reversed(self, index: u32) -> bool {
108 match self {
109 PlaybackDirection::Normal => false,
110 PlaybackDirection::Reverse => true,
111 PlaybackDirection::Alternate => !index.is_multiple_of(2),
112 PlaybackDirection::AlternateReverse => index.is_multiple_of(2),
113 }
114 }
115
116 fn alternates(self) -> bool {
117 matches!(
118 self,
119 PlaybackDirection::Alternate | PlaybackDirection::AlternateReverse
120 )
121 }
122}
123
124#[derive(Debug, Clone, Copy, PartialEq)]
127#[non_exhaustive]
128pub struct KeyframeTiming {
129 pub duration_ms: f32,
131 pub delay_ms: f32,
133 pub easing: Easing,
136 pub iterations: Option<u32>,
138 pub direction: PlaybackDirection,
140 pub frame_rate: Option<f32>,
143}
144
145impl Default for KeyframeTiming {
146 fn default() -> Self {
147 Self {
148 duration_ms: 300.0,
149 delay_ms: 0.0,
150 easing: Easing::EASE,
151 iterations: Some(1),
152 direction: PlaybackDirection::Normal,
153 frame_rate: None,
154 }
155 }
156}
157
158impl KeyframeTiming {
159 pub fn new(duration_ms: f32) -> Self {
161 Self {
162 duration_ms,
163 ..Self::default()
164 }
165 }
166
167 pub fn easing(mut self, easing: Easing) -> Self {
169 self.easing = easing;
170 self
171 }
172
173 pub fn delay(mut self, delay_ms: f32) -> Self {
175 self.delay_ms = delay_ms;
176 self
177 }
178
179 pub fn iterations(mut self, iterations: Option<u32>) -> Self {
181 self.iterations = iterations;
182 self
183 }
184
185 pub fn infinite(self) -> Self {
187 self.iterations(None)
188 }
189
190 pub fn direction(mut self, direction: PlaybackDirection) -> Self {
192 self.direction = direction;
193 self
194 }
195
196 pub fn frame_rate(mut self, hz: f32) -> Self {
198 self.frame_rate = Some(hz);
199 self
200 }
201}
202
203fn resolve(frames: &[Keyframe]) -> Vec<(f32, f32, Option<Easing>)> {
208 let n = frames.len();
209 let mut offsets: Vec<Option<f32>> = frames
210 .iter()
211 .map(|f| {
212 f.offset
213 .filter(|o| o.is_finite())
214 .map(|o| o.clamp(0.0, 1.0))
215 })
216 .collect();
217 if n == 1 {
218 offsets[0].get_or_insert(1.0);
219 } else if n > 1 {
220 offsets[0].get_or_insert(0.0);
221 offsets[n - 1].get_or_insert(1.0);
222 }
223 let mut i = 0;
224 while i < n {
225 if offsets[i].is_some() {
226 i += 1;
227 continue;
228 }
229 let start = i - 1;
230 let mut end = i;
231 while offsets[end].is_none() {
232 end += 1;
233 }
234 let (a, b) = (offsets[start].unwrap_or(0.0), offsets[end].unwrap_or(1.0));
235 for (k, slot) in offsets.iter_mut().enumerate().take(end).skip(i) {
236 *slot = Some(a + (b - a) * (k - start) as f32 / (end - start) as f32);
237 }
238 i = end;
239 }
240 let mut last = 0.0f32;
242 frames
243 .iter()
244 .zip(offsets)
245 .map(|(f, o)| {
246 let o = o.unwrap_or(1.0).max(last);
247 last = o;
248 (o, f.value, f.easing)
249 })
250 .collect()
251}
252
253fn iteration(
255 node: NodeId,
256 frames: &[(f32, f32, Option<Easing>)],
257 timing: &KeyframeTiming,
258 backwards: bool,
259) -> Composite {
260 let duration = timing.duration_ms.max(0.0);
261 let oriented: Vec<(f32, f32, Easing)> = if backwards {
263 let mut out = Vec::with_capacity(frames.len());
264 for i in (0..frames.len()).rev() {
265 let easing = match i {
266 0 => timing.easing,
267 _ => frames[i - 1].2.unwrap_or(timing.easing).reversed(),
268 };
269 out.push((1.0 - frames[i].0, frames[i].1, easing));
270 }
271 out
272 } else {
273 frames
274 .iter()
275 .map(|&(o, v, e)| (o, v, e.unwrap_or(timing.easing)))
276 .collect()
277 };
278 let timing_to = |to: f32, ms: f32, easing: Easing| Composite::Run {
279 node,
280 driver: Driver::Timing {
281 to,
282 duration_ms: ms,
283 easing,
284 delay_ms: 0.0,
285 frame_rate: timing.frame_rate,
286 },
287 };
288 let mut steps = Vec::with_capacity(oriented.len() + 1);
289 let Some(&(first_offset, first_value, _)) = oriented.first() else {
290 return Composite::Sequence(steps);
291 };
292 steps.push(timing_to(
295 first_value,
296 first_offset * duration,
297 timing.easing,
298 ));
299 for pair in oriented.windows(2) {
300 let ((a, _, easing), (b, value, _)) = (pair[0], pair[1]);
301 steps.push(timing_to(value, (b - a) * duration, easing));
302 }
303 let last = oriented.last().map_or(1.0, |f| f.0);
304 if last < 1.0 {
305 steps.push(Composite::Delay((1.0 - last) * duration));
306 }
307 Composite::Sequence(steps)
308}
309
310pub fn keyframes(node: NodeId, frames: &[Keyframe], timing: &KeyframeTiming) -> Composite {
317 let frames = resolve(frames);
318 let pass = |index| iteration(node, &frames, timing, timing.direction.reversed(index));
319 let body = match (timing.iterations, timing.direction.alternates()) {
320 (Some(0), _) => Composite::Sequence(Vec::new()),
321 (Some(1), _) => pass(0),
322 (iterations, false) => Composite::Loop {
323 child: Box::new(pass(0)),
324 iterations,
325 reset: false,
326 },
327 (None, true) => Composite::Loop {
328 child: Box::new(Composite::Sequence(vec![pass(0), pass(1)])),
329 iterations: None,
330 reset: false,
331 },
332 (Some(n), true) => {
333 let pairs = Composite::Loop {
334 child: Box::new(Composite::Sequence(vec![pass(0), pass(1)])),
335 iterations: Some(n / 2),
336 reset: false,
337 };
338 match n % 2 {
339 0 => pairs,
340 _ => Composite::Sequence(vec![pairs, pass(0)]),
341 }
342 }
343 };
344 if timing.delay_ms <= 0.0 {
345 return body;
346 }
347 let mut steps = Vec::with_capacity(3);
351 let first = if timing.direction.reversed(0) {
352 frames.last().map(|f| (1.0 - f.0, f.1))
353 } else {
354 frames.first().map(|f| (f.0, f.1))
355 };
356 if let Some((0.0, value)) = first {
357 steps.push(Composite::Run {
358 node,
359 driver: Driver::Timing {
360 to: value,
361 duration_ms: 0.0,
362 easing: Easing::Linear,
363 delay_ms: 0.0,
364 frame_rate: timing.frame_rate,
365 },
366 });
367 }
368 steps.push(Composite::Delay(timing.delay_ms));
369 steps.push(body);
370 Composite::Sequence(steps)
371}
372
373pub fn keyframe_ends(frames: &[Keyframe], timing: &KeyframeTiming) -> Option<(f32, f32)> {
376 let (first, last) = (frames.first()?.value, frames.last()?.value);
377 let at = |backwards| if backwards { last } else { first };
378 let start = at(timing.direction.reversed(0));
379 let end = match timing.iterations {
380 Some(0) => start,
381 Some(n) => {
382 if timing.direction.reversed(n - 1) {
383 first
384 } else {
385 last
386 }
387 }
388 None => {
390 if timing.direction.reversed(0) {
391 first
392 } else {
393 last
394 }
395 }
396 };
397 Some((start, end))
398}
399
400#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
402pub enum StaggerFrom {
403 #[default]
406 First,
407 Last,
409 Center,
411 Index(usize),
413}
414
415pub fn stagger_delay(index: usize, count: usize, from: StaggerFrom) -> f32 {
417 if count == 0 {
418 return 0.0;
419 }
420 let index = index.min(count - 1);
421 match from {
422 StaggerFrom::First => index as f32,
423 StaggerFrom::Last => (count - 1 - index) as f32,
424 StaggerFrom::Center => (index as f32 - (count - 1) as f32 / 2.0).abs().floor(),
426 StaggerFrom::Index(origin) => index.abs_diff(origin.min(count - 1)) as f32,
427 }
428}
429
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
434pub enum MotionChannel {
435 Opacity,
437 TranslateX,
439 TranslateY,
441 Rotate,
443 RotateX,
445 RotateY,
447 Scale,
449 ScaleX,
451 ScaleY,
453}
454
455impl MotionChannel {
456 pub const ALL: [MotionChannel; 9] = [
458 MotionChannel::Opacity,
459 MotionChannel::TranslateX,
460 MotionChannel::TranslateY,
461 MotionChannel::Rotate,
462 MotionChannel::RotateX,
463 MotionChannel::RotateY,
464 MotionChannel::Scale,
465 MotionChannel::ScaleX,
466 MotionChannel::ScaleY,
467 ];
468
469 pub fn index(self) -> usize {
471 self as usize
472 }
473
474 pub fn name(self) -> &'static str {
476 match self {
477 MotionChannel::Opacity => "opacity",
478 MotionChannel::TranslateX => "translateX",
479 MotionChannel::TranslateY => "translateY",
480 MotionChannel::Rotate => "rotate",
481 MotionChannel::RotateX => "rotateX",
482 MotionChannel::RotateY => "rotateY",
483 MotionChannel::Scale => "scale",
484 MotionChannel::ScaleX => "scaleX",
485 MotionChannel::ScaleY => "scaleY",
486 }
487 }
488
489 pub fn parse(name: &str) -> Option<MotionChannel> {
491 MotionChannel::ALL.into_iter().find(|c| c.name() == name)
492 }
493
494 pub fn identity(self) -> f32 {
496 match self {
497 MotionChannel::Opacity
498 | MotionChannel::Scale
499 | MotionChannel::ScaleX
500 | MotionChannel::ScaleY => 1.0,
501 _ => 0.0,
502 }
503 }
504
505 pub fn transform(self) -> Option<TransformKind> {
507 Some(match self {
508 MotionChannel::Opacity => return None,
509 MotionChannel::TranslateX => TransformKind::TranslateX,
510 MotionChannel::TranslateY => TransformKind::TranslateY,
511 MotionChannel::Rotate => TransformKind::Rotate,
512 MotionChannel::RotateX => TransformKind::RotateX,
513 MotionChannel::RotateY => TransformKind::RotateY,
514 MotionChannel::Scale => TransformKind::Scale,
515 MotionChannel::ScaleX => TransformKind::ScaleX,
516 MotionChannel::ScaleY => TransformKind::ScaleY,
517 })
518 }
519}
520
521#[derive(Debug, Clone, PartialEq, Default)]
524#[non_exhaustive]
525pub struct MotionSpec {
526 pub tracks: Vec<(MotionChannel, Vec<Keyframe>)>,
528 pub timing: KeyframeTiming,
530 pub spring: Option<Spring>,
538}
539
540impl MotionSpec {
541 pub fn new(timing: KeyframeTiming) -> Self {
543 Self {
544 tracks: Vec::new(),
545 timing,
546 spring: None,
547 }
548 }
549
550 pub fn track(
552 mut self,
553 channel: MotionChannel,
554 frames: impl IntoIterator<Item = Keyframe>,
555 ) -> Self {
556 let frames: Vec<Keyframe> = frames.into_iter().collect();
557 match self.tracks.iter_mut().find(|(c, _)| *c == channel) {
558 Some((_, f)) => *f = frames,
559 None => self.tracks.push((channel, frames)),
560 }
561 self
562 }
563
564 pub fn values(self, channel: MotionChannel, values: impl IntoIterator<Item = f32>) -> Self {
566 self.track(channel, values.into_iter().map(Keyframe::new))
567 }
568
569 pub fn timing(mut self, f: impl FnOnce(KeyframeTiming) -> KeyframeTiming) -> Self {
571 self.timing = f(self.timing);
572 self
573 }
574
575 pub fn spring(mut self, spring: Spring) -> Self {
577 self.spring = Some(spring);
578 self
579 }
580
581 fn end(&self, frames: &[Keyframe]) -> Option<f32> {
583 let timing = match self.spring {
584 Some(_) => KeyframeTiming {
585 iterations: Some(1),
586 ..self.timing
587 },
588 None => self.timing,
589 };
590 keyframe_ends(frames, &timing).map(|(_, end)| end)
591 }
592
593 pub fn composite(&self, nodes: &[NodeId; 9], reduced: bool) -> Composite {
597 let mut children = Vec::with_capacity(self.tracks.len());
598 for (channel, frames) in &self.tracks {
599 let node = nodes[channel.index()];
600 if reduced {
601 let Some(end) = self.end(frames) else {
602 continue;
603 };
604 children.push(Composite::Run {
605 node,
606 driver: Driver::Timing {
607 to: end,
608 duration_ms: 0.0,
609 easing: Easing::Linear,
610 delay_ms: 0.0,
611 frame_rate: self.timing.frame_rate,
612 },
613 });
614 } else if let Some(spring) = self.spring {
615 let Some(to) = self.end(frames) else {
616 continue;
617 };
618 children.push(Composite::Run {
619 node,
620 driver: Driver::Spring {
621 to,
622 stiffness: spring.stiffness,
623 damping: spring.damping,
624 mass: spring.mass,
625 velocity: None,
626 frame_rate: spring.frame_rate.or(self.timing.frame_rate),
627 },
628 });
629 } else {
630 children.push(keyframes(node, frames, &self.timing));
631 }
632 }
633 let all = Composite::Parallel {
634 children,
635 stop_together: true,
636 };
637 match self.spring {
640 Some(_) if !reduced && self.timing.delay_ms > 0.0 => {
641 Composite::Sequence(vec![Composite::Delay(self.timing.delay_ms), all])
642 }
643 _ => all,
644 }
645 }
646
647 pub fn start_values(&self) -> impl Iterator<Item = (MotionChannel, f32)> + '_ {
650 self.tracks.iter().filter_map(|(channel, frames)| {
651 Some((*channel, keyframe_ends(frames, &self.timing)?.0))
652 })
653 }
654}
655
656#[derive(Debug, Clone, Copy, PartialEq, Eq)]
658pub enum MotionKind {
659 Enter,
661 Exit,
663 Attention,
665 Loop,
667}
668
669impl MotionKind {
670 pub fn name(self) -> &'static str {
672 match self {
673 MotionKind::Enter => "enter",
674 MotionKind::Exit => "exit",
675 MotionKind::Attention => "attention",
676 MotionKind::Loop => "loop",
677 }
678 }
679}
680
681type Track = (MotionChannel, &'static [(f32, f32)]);
683
684#[derive(Debug)]
686pub struct PresetDef {
687 pub name: &'static str,
689 pub kind: MotionKind,
691 pub doc: &'static str,
693 duration_ms: f32,
694 easing: Easing,
695 iterations: Option<u32>,
696 direction: PlaybackDirection,
697 tracks: &'static [Track],
698}
699
700impl PresetDef {
701 pub fn spec(&self) -> MotionSpec {
703 let timing = KeyframeTiming {
704 duration_ms: self.duration_ms,
705 easing: self.easing,
706 iterations: self.iterations,
707 direction: self.direction,
708 ..KeyframeTiming::default()
709 };
710 let mut spec = MotionSpec::new(timing);
711 for (channel, frames) in self.tracks {
712 spec = spec.track(*channel, frames.iter().map(|&(o, v)| Keyframe::at(o, v)));
713 }
714 spec
715 }
716}
717
718use MotionChannel::{
719 Opacity as O, Rotate as R, RotateX as RX, RotateY as RY, Scale as S, ScaleX as SX,
720 ScaleY as SY, TranslateX as X, TranslateY as Y,
721};
722
723const OUT_EXPO: Easing = Easing::Bezier(0.16, 1.0, 0.3, 1.0);
725const IN_QUART: Easing = Easing::Bezier(0.5, 0.0, 0.75, 0.0);
727const OUT_BACK: Easing = Easing::Bezier(0.34, 1.56, 0.64, 1.0);
729const IN_OUT_SINE: Easing = Easing::Bezier(0.37, 0.0, 0.63, 1.0);
730
731macro_rules! presets {
732 ($(
733 $(#[doc = $doc:literal])+
734 $variant:ident $name:literal $kind:ident $ms:literal $easing:expr, $iterations:expr, $direction:ident
735 [$($channel:ident: [$(($o:literal, $v:literal)),* $(,)?]),* $(,)?]
736 )*) => {
737 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
742 #[non_exhaustive]
743 pub enum MotionPreset {
744 $($(#[doc = $doc])+ $variant,)*
745 }
746
747 pub const PRESETS: &[PresetDef] = &[$(
749 PresetDef {
750 name: $name,
751 kind: MotionKind::$kind,
752 doc: concat!($($doc),+),
753 duration_ms: $ms,
754 easing: $easing,
755 iterations: $iterations,
756 direction: PlaybackDirection::$direction,
757 tracks: &[$(($channel, &[$(($o, $v)),*])),*],
758 },
759 )*];
760
761 impl MotionPreset {
762 pub const ALL: &[MotionPreset] = &[$(MotionPreset::$variant),*];
764 }
765 };
766}
767
768presets! {
769 FadeIn "fadeIn" Enter 300.0 Easing::EaseOut, Some(1), Normal [O: [(0.0, 0.0), (1.0, 1.0)]]
771 FadeInUp "fadeInUp" Enter 450.0 OUT_EXPO, Some(1), Normal
773 [O: [(0.0, 0.0), (1.0, 1.0)], Y: [(0.0, 24.0), (1.0, 0.0)]]
774 FadeInDown "fadeInDown" Enter 450.0 OUT_EXPO, Some(1), Normal
776 [O: [(0.0, 0.0), (1.0, 1.0)], Y: [(0.0, -24.0), (1.0, 0.0)]]
777 FadeInLeft "fadeInLeft" Enter 450.0 OUT_EXPO, Some(1), Normal
779 [O: [(0.0, 0.0), (1.0, 1.0)], X: [(0.0, -24.0), (1.0, 0.0)]]
780 FadeInRight "fadeInRight" Enter 450.0 OUT_EXPO, Some(1), Normal
782 [O: [(0.0, 0.0), (1.0, 1.0)], X: [(0.0, 24.0), (1.0, 0.0)]]
783 ZoomIn "zoomIn" Enter 350.0 OUT_EXPO, Some(1), Normal
785 [O: [(0.0, 0.0), (1.0, 1.0)], S: [(0.0, 0.9), (1.0, 1.0)]]
786 PopIn "popIn" Enter 450.0 OUT_BACK, Some(1), Normal
788 [O: [(0.0, 0.0), (0.4, 1.0), (1.0, 1.0)], S: [(0.0, 0.5), (1.0, 1.0)]]
789 BounceIn "bounceIn" Enter 650.0 Easing::Bezier(0.215, 0.61, 0.355, 1.0), Some(1), Normal
791 [O: [(0.0, 0.0), (0.6, 1.0), (1.0, 1.0)],
792 S: [(0.0, 0.3), (0.2, 1.1), (0.4, 0.9), (0.6, 1.03), (0.8, 0.97), (1.0, 1.0)]]
793 SlideInUp "slideInUp" Enter 400.0 OUT_EXPO, Some(1), Normal [Y: [(0.0, 64.0), (1.0, 0.0)]]
795 SlideInDown "slideInDown" Enter 400.0 OUT_EXPO, Some(1), Normal [Y: [(0.0, -64.0), (1.0, 0.0)]]
797 FlipInX "flipInX" Enter 600.0 Easing::EaseOut, Some(1), Normal
799 [O: [(0.0, 0.0), (0.6, 1.0), (1.0, 1.0)], RX: [(0.0, 90.0), (0.4, -20.0), (0.6, 10.0), (0.8, -5.0), (1.0, 0.0)]]
800 FlipInY "flipInY" Enter 600.0 Easing::EaseOut, Some(1), Normal
802 [O: [(0.0, 0.0), (0.6, 1.0), (1.0, 1.0)], RY: [(0.0, 90.0), (0.4, -20.0), (0.6, 10.0), (0.8, -5.0), (1.0, 0.0)]]
803 FadeOut "fadeOut" Exit 250.0 Easing::EaseIn, Some(1), Normal [O: [(0.0, 1.0), (1.0, 0.0)]]
805 FadeOutUp "fadeOutUp" Exit 300.0 IN_QUART, Some(1), Normal
807 [O: [(0.0, 1.0), (1.0, 0.0)], Y: [(0.0, 0.0), (1.0, -24.0)]]
808 FadeOutDown "fadeOutDown" Exit 300.0 IN_QUART, Some(1), Normal
810 [O: [(0.0, 1.0), (1.0, 0.0)], Y: [(0.0, 0.0), (1.0, 24.0)]]
811 FadeOutLeft "fadeOutLeft" Exit 300.0 IN_QUART, Some(1), Normal
813 [O: [(0.0, 1.0), (1.0, 0.0)], X: [(0.0, 0.0), (1.0, -24.0)]]
814 FadeOutRight "fadeOutRight" Exit 300.0 IN_QUART, Some(1), Normal
816 [O: [(0.0, 1.0), (1.0, 0.0)], X: [(0.0, 0.0), (1.0, 24.0)]]
817 ZoomOut "zoomOut" Exit 250.0 IN_QUART, Some(1), Normal
819 [O: [(0.0, 1.0), (1.0, 0.0)], S: [(0.0, 1.0), (1.0, 0.9)]]
820 PopOut "popOut" Exit 300.0 Easing::EaseIn, Some(1), Normal
822 [O: [(0.0, 1.0), (0.3, 1.0), (1.0, 0.0)], S: [(0.0, 1.0), (0.3, 1.08), (1.0, 0.5)]]
823 SlideOutDown "slideOutDown" Exit 300.0 IN_QUART, Some(1), Normal [Y: [(0.0, 0.0), (1.0, 64.0)]]
825 SlideOutUp "slideOutUp" Exit 300.0 IN_QUART, Some(1), Normal [Y: [(0.0, 0.0), (1.0, -64.0)]]
827 Shake "shake" Attention 500.0 Easing::EaseInOut, Some(1), Normal
829 [X: [(0.0, 0.0), (0.1, -8.0), (0.3, 8.0), (0.5, -8.0), (0.7, 8.0), (0.9, -4.0), (1.0, 0.0)]]
830 HeadShake "headShake" Attention 800.0 Easing::EaseInOut, Some(1), Normal
832 [X: [(0.0, 0.0), (0.065, -6.0), (0.185, 5.0), (0.315, -3.0), (0.435, 2.0), (0.5, 0.0), (1.0, 0.0)],
833 RY: [(0.0, 0.0), (0.065, -9.0), (0.185, 7.0), (0.315, -5.0), (0.435, 3.0), (0.5, 0.0), (1.0, 0.0)]]
834 Wiggle "wiggle" Attention 600.0 Easing::EaseInOut, Some(1), Normal
836 [R: [(0.0, 0.0), (0.15, -6.0), (0.3, 6.0), (0.45, -4.0), (0.6, 4.0), (0.75, -2.0), (1.0, 0.0)]]
837 Swing "swing" Attention 900.0 Easing::EaseInOut, Some(1), Normal
840 [R: [(0.0, 0.0), (0.2, 15.0), (0.4, -10.0), (0.6, 5.0), (0.8, -5.0), (1.0, 0.0)]]
841 Pulse "pulse" Attention 500.0 Easing::EaseInOut, Some(1), Normal
843 [S: [(0.0, 1.0), (0.5, 1.06), (1.0, 1.0)]]
844 Heartbeat "heartbeat" Attention 900.0 Easing::EaseInOut, Some(1), Normal
846 [S: [(0.0, 1.0), (0.14, 1.25), (0.28, 1.0), (0.42, 1.25), (0.7, 1.0), (1.0, 1.0)]]
847 RubberBand "rubberBand" Attention 800.0 Easing::EaseInOut, Some(1), Normal
849 [SX: [(0.0, 1.0), (0.3, 1.25), (0.4, 0.75), (0.5, 1.15), (0.65, 0.95), (0.75, 1.05), (1.0, 1.0)],
850 SY: [(0.0, 1.0), (0.3, 0.75), (0.4, 1.25), (0.5, 0.85), (0.65, 1.05), (0.75, 0.95), (1.0, 1.0)]]
851 Jello "jello" Attention 800.0 Easing::EaseInOut, Some(1), Normal
853 [SX: [(0.0, 1.0), (0.2, 1.12), (0.4, 0.92), (0.6, 1.05), (0.8, 0.98), (1.0, 1.0)],
854 SY: [(0.0, 1.0), (0.2, 0.88), (0.4, 1.08), (0.6, 0.95), (0.8, 1.02), (1.0, 1.0)]]
855 Tada "tada" Attention 900.0 Easing::EaseInOut, Some(1), Normal
857 [S: [(0.0, 1.0), (0.1, 0.9), (0.2, 0.9), (0.3, 1.1), (0.9, 1.1), (1.0, 1.0)],
858 R: [(0.0, 0.0), (0.1, -3.0), (0.2, -3.0), (0.3, 3.0), (0.4, -3.0), (0.5, 3.0), (0.6, -3.0), (0.7, 3.0), (0.8, -3.0), (0.9, 3.0), (1.0, 0.0)]]
859 Jump "jump" Attention 700.0 Easing::EaseInOut, Some(1), Normal
861 [Y: [(0.0, 0.0), (0.4, -18.0), (0.55, -18.0), (0.8, 0.0), (1.0, 0.0)],
862 SY: [(0.0, 1.0), (0.15, 0.9), (0.4, 1.05), (0.8, 0.92), (1.0, 1.0)]]
863 Flash "flash" Attention 800.0 Easing::Linear, Some(1), Normal
865 [O: [(0.0, 1.0), (0.25, 0.0), (0.5, 1.0), (0.75, 0.0), (1.0, 1.0)]]
866 Spin "spin" Loop 1000.0 Easing::Linear, None, Normal [R: [(0.0, 0.0), (1.0, 360.0)]]
868 Float "float" Loop 1500.0 IN_OUT_SINE, None, Alternate [Y: [(0.0, 0.0), (1.0, -8.0)]]
870 Breathe "breathe" Loop 1800.0 IN_OUT_SINE, None, Alternate
872 [S: [(0.0, 1.0), (1.0, 1.05)], O: [(0.0, 1.0), (1.0, 0.8)]]
873 Sway "sway" Loop 1600.0 IN_OUT_SINE, None, Alternate [R: [(0.0, -4.0), (1.0, 4.0)]]
875 Bob "bob" Loop 1000.0 Easing::Linear, None, Normal
877 [Y: [(0.0, 0.0), (0.5, -12.0), (1.0, 0.0)]]
878 Glow "glow" Loop 2000.0 Easing::Bezier(0.4, 0.0, 0.6, 1.0), None, Normal
880 [O: [(0.0, 1.0), (0.5, 0.5), (1.0, 1.0)]]
881}
882
883impl MotionPreset {
884 pub fn def(self) -> &'static PresetDef {
886 &PRESETS[self as usize]
887 }
888
889 pub fn name(self) -> &'static str {
891 self.def().name
892 }
893
894 pub fn parse(name: &str) -> Option<MotionPreset> {
896 MotionPreset::ALL.iter().copied().find(|p| p.name() == name)
897 }
898
899 pub fn spec(self) -> MotionSpec {
901 self.def().spec()
902 }
903}
904
905impl From<MotionPreset> for MotionSpec {
906 fn from(preset: MotionPreset) -> Self {
907 preset.spec()
908 }
909}
910
911#[cfg(test)]
912mod tests {
913 use super::*;
914 use crate::animation::{AnimationOp, Finished, Graph};
915
916 fn value(g: &mut Graph, node: NodeId, start: f32) {
917 g.apply(
918 AnimationOp::CreateValue { node, value: start },
919 &mut Vec::new(),
920 );
921 }
922
923 fn run(spec: Composite, start: f32, times: &[f64]) -> (Vec<f32>, Vec<Finished>) {
925 let mut g = Graph::default();
926 value(&mut g, 2, start);
927 let mut f = Vec::new();
928 g.apply(
929 AnimationOp::StartComposite {
930 animation: 10,
931 key: 12,
932 spec,
933 },
934 &mut f,
935 );
936 let mut out = Vec::new();
939 let mut now = 0.0;
940 for &t in times {
941 while now + 10.0 < t {
942 now += 10.0;
943 g.tick(now / 1000.0, &mut f);
944 }
945 now = t;
946 g.tick(t / 1000.0, &mut f);
947 out.push((g.value(2).unwrap() * 1000.0).round() / 1000.0);
948 }
949 (out, f)
950 }
951
952 fn linear(ms: f32) -> KeyframeTiming {
953 KeyframeTiming::new(ms).easing(Easing::Linear)
954 }
955
956 #[test]
957 fn offsets_spread_as_the_web_animations_api_spreads_them() {
958 let frames = [
959 Keyframe::new(0.0),
960 Keyframe::new(1.0),
961 Keyframe::at(0.8, 2.0),
962 Keyframe::new(3.0),
963 ];
964 let resolved: Vec<f32> = resolve(&frames).iter().map(|f| f.0).collect();
965 assert_eq!(resolved, [0.0, 0.4, 0.8, 1.0]);
966 assert_eq!(resolve(&[Keyframe::new(5.0)])[0].0, 1.0);
967 let held: Vec<f32> = resolve(&[Keyframe::at(0.5, 0.0), Keyframe::at(0.2, 1.0)])
969 .iter()
970 .map(|f| f.0)
971 .collect();
972 assert_eq!(held, [0.5, 0.5]);
973 }
974
975 #[test]
976 fn keyframes_play_their_segments_on_time() {
977 let frames = [
978 Keyframe::new(0.0),
979 Keyframe::at(0.25, 10.0),
980 Keyframe::new(0.0),
981 ];
982 let spec = keyframes(2, &frames, &linear(400.0));
983 let (values, f) = run(spec, 7.0, &[0.0, 50.0, 100.0, 250.0, 400.0, 450.0]);
985 assert_eq!(values, [0.0, 5.0, 10.0, 5.0, 0.0, 0.0]);
986 assert!(f.iter().any(|f| f.animation == 10 && f.finished), "{f:?}");
987 }
988
989 #[test]
990 fn directions_iterations_and_delays() {
991 let frames = [Keyframe::new(0.0), Keyframe::new(10.0)];
992 let alternate = linear(100.0)
993 .direction(PlaybackDirection::Alternate)
994 .iterations(Some(3));
995 let (values, _) = run(
996 keyframes(2, &frames, &alternate),
997 0.0,
998 &[0.0, 50.0, 150.0, 250.0, 300.0, 400.0],
999 );
1000 assert_eq!(values, [0.0, 5.0, 5.0, 5.0, 10.0, 10.0]);
1001 let reverse = linear(100.0)
1002 .direction(PlaybackDirection::Reverse)
1003 .delay(100.0);
1004 let (values, _) = run(
1005 keyframes(2, &frames, &reverse),
1006 3.0,
1007 &[0.0, 50.0, 150.0, 200.0],
1008 );
1009 assert_eq!(values, [10.0, 10.0, 5.0, 0.0]);
1011 let (values, f) = run(
1013 keyframes(2, &frames, &linear(100.0).infinite()),
1014 0.0,
1015 &[0.0, 10_050.0],
1016 );
1017 assert_eq!(values[1], 5.0);
1018 assert!(!f.iter().any(|f| f.animation == 10), "{f:?}");
1019 assert_eq!(
1020 keyframe_ends(&frames, &alternate.iterations(Some(2))),
1021 Some((0.0, 0.0))
1022 );
1023 }
1024
1025 #[test]
1026 fn a_reversed_segment_runs_its_curve_backwards() {
1027 let ease = Easing::Bezier(0.42, 0.0, 1.0, 1.0);
1028 let frames = [Keyframe::new(0.0).ease(ease), Keyframe::new(1.0)];
1029 let timing = KeyframeTiming::new(100.0).direction(PlaybackDirection::Reverse);
1030 let (backwards, _) = run(keyframes(2, &frames, &timing), 0.0, &[0.0, 25.0]);
1031 let (forwards, _) = run(
1032 keyframes(2, &frames, &KeyframeTiming::new(100.0)),
1033 0.0,
1034 &[0.0, 75.0],
1035 );
1036 assert!(
1037 (backwards[1] - forwards[1]).abs() < 1e-3,
1038 "{backwards:?} {forwards:?}"
1039 );
1040 }
1041
1042 #[test]
1043 fn steps_jump_as_in_css() {
1044 use super::super::sample_easing;
1045 use crate::animation::StepPosition::*;
1046 let at = |e| sample_easing(Easing::Steps(4, e), 5);
1047 assert_eq!(at(JumpEnd), [0.0, 0.25, 0.5, 0.75, 1.0]);
1048 assert_eq!(at(JumpStart), [0.25, 0.5, 0.75, 1.0, 1.0]);
1049 let none = sample_easing(Easing::Steps(3, JumpNone), 4);
1050 assert_eq!(none, [0.0, 0.5, 1.0, 1.0]);
1051 let both = sample_easing(Easing::Steps(1, JumpBoth), 3);
1052 assert_eq!(both, [0.5, 0.5, 1.0]);
1053 assert_eq!(
1054 Easing::Steps(2, JumpStart).reversed(),
1055 Easing::Steps(2, JumpEnd)
1056 );
1057 }
1058
1059 #[test]
1060 fn staggering_counts_from_its_origin() {
1061 let delays = |from| {
1062 (0..5)
1063 .map(|i| stagger_delay(i, 5, from))
1064 .collect::<Vec<_>>()
1065 };
1066 assert_eq!(delays(StaggerFrom::First), [0.0, 1.0, 2.0, 3.0, 4.0]);
1067 assert_eq!(delays(StaggerFrom::Last), [4.0, 3.0, 2.0, 1.0, 0.0]);
1068 assert_eq!(delays(StaggerFrom::Center), [2.0, 1.0, 0.0, 1.0, 2.0]);
1069 assert_eq!(delays(StaggerFrom::Index(1)), [1.0, 0.0, 1.0, 2.0, 3.0]);
1070 let even: Vec<f32> = (0..4)
1071 .map(|i| stagger_delay(i, 4, StaggerFrom::Center))
1072 .collect();
1073 assert_eq!(even, [1.0, 0.0, 0.0, 1.0]);
1074 }
1075
1076 #[test]
1077 fn presets_are_well_formed() {
1078 assert_eq!(PRESETS.len(), MotionPreset::ALL.len());
1079 for (i, preset) in MotionPreset::ALL.iter().enumerate() {
1080 let def = preset.def();
1081 assert_eq!(def.name, PRESETS[i].name);
1082 assert_eq!(MotionPreset::parse(def.name), Some(*preset));
1083 let spec = preset.spec();
1084 assert!(!spec.tracks.is_empty(), "{}", def.name);
1085 for (channel, frames) in &spec.tracks {
1086 let resolved = resolve(frames);
1087 assert_eq!(resolved.first().map(|f| f.0), Some(0.0), "{}", def.name);
1088 assert_eq!(resolved.last().map(|f| f.0), Some(1.0), "{}", def.name);
1089 assert!(
1090 resolved.windows(2).all(|w| w[0].0 <= w[1].0),
1091 "{}",
1092 def.name
1093 );
1094 let (start, end) = keyframe_ends(frames, &spec.timing).unwrap();
1095 let rest = channel.identity();
1096 match def.kind {
1097 MotionKind::Enter => assert_eq!(end, rest, "{} ends at rest", def.name),
1098 MotionKind::Exit => assert_eq!(start, rest, "{} starts at rest", def.name),
1099 MotionKind::Attention => {
1100 assert_eq!((start, end), (rest, rest), "{}", def.name)
1101 }
1102 MotionKind::Loop => assert!(spec.timing.iterations.is_none(), "{}", def.name),
1103 }
1104 }
1105 }
1106 }
1107
1108 fn csp_spring() -> Spring {
1110 Spring {
1111 stiffness: 620.0,
1112 damping: 36.0,
1113 ..Spring::default()
1114 }
1115 }
1116
1117 #[test]
1118 fn a_spring_motion_springs_each_channel_to_where_it_ends() {
1119 let spec = MotionPreset::FadeInUp.spec().spring(csp_spring());
1120 let nodes = [2, 4, 6, 8, 10, 12, 14, 16, 18];
1121 let Composite::Parallel { children, .. } = spec.composite(&nodes, false) else {
1122 panic!()
1123 };
1124 let targets: Vec<_> = children
1125 .iter()
1126 .map(|child| match child {
1127 Composite::Run {
1128 node,
1129 driver:
1130 Driver::Spring {
1131 to,
1132 stiffness,
1133 velocity: None,
1134 ..
1135 },
1136 } => (*node, *to, *stiffness),
1137 other => panic!("{other:?}"),
1138 })
1139 .collect();
1140 assert_eq!(targets, [(2, 1.0, 620.0), (6, 0.0, 620.0)]);
1141 let track = MotionSpec::default()
1144 .values(MotionChannel::Opacity, [0.0, 10.0])
1145 .spring(csp_spring());
1146 let mut nodes = [0; 9];
1147 nodes[MotionChannel::Opacity.index()] = 2;
1148 let (values, f) = run(
1149 track.composite(&nodes, false),
1150 5.0,
1151 &[0.0, 120.0, 200.0, 1000.0],
1152 );
1153 assert_eq!(values[0], 5.0);
1154 assert!(values[1] > 5.0 && values[1] < 10.0, "{values:?}");
1155 assert!(values[2] > 10.0, "{values:?}");
1156 assert_eq!(values[3], 10.0);
1157 assert!(f.iter().any(|f| f.animation == 10 && f.finished), "{f:?}");
1158 let delayed = track.clone().timing(|t| t.delay(100.0));
1160 let (values, _) = run(delayed.composite(&nodes, false), 5.0, &[0.0, 90.0, 200.0]);
1161 assert_eq!(values[..2], [5.0, 5.0]);
1162 assert!(values[2] > 5.0, "{values:?}");
1163 let (values, _) = run(track.composite(&nodes, true), 5.0, &[0.0]);
1165 assert_eq!(values, [10.0]);
1166 }
1167
1168 #[test]
1169 fn an_interrupted_spring_motion_goes_on_from_its_value_and_velocity() {
1170 let mut nodes = [0; 9];
1171 nodes[MotionChannel::TranslateY.index()] = 2;
1172 let to = |end: f32| {
1173 MotionSpec::default()
1174 .values(MotionChannel::TranslateY, [100.0, end])
1175 .spring(csp_spring())
1176 .composite(&nodes, false)
1177 };
1178 let mut g = Graph::default();
1179 value(&mut g, 2, 100.0);
1180 let mut f = Vec::new();
1181 let start = |g: &mut Graph, animation, spec, f: &mut Vec<Finished>| {
1182 g.apply(
1183 AnimationOp::StartComposite {
1184 animation,
1185 key: 12,
1186 spec,
1187 },
1188 f,
1189 )
1190 };
1191 start(&mut g, 10, to(0.0), &mut f);
1192 let mut now = 0.0;
1193 while now < 80.0 {
1194 g.tick(now / 1000.0, &mut f);
1195 now += 10.0;
1196 }
1197 let before = g.value(2).unwrap();
1198 assert!(before < 100.0 && before > 0.0, "{before}");
1199 start(&mut g, 11, to(100.0), &mut f);
1202 g.tick(now / 1000.0, &mut f);
1203 let at_once = g.value(2).unwrap();
1204 g.tick((now + 10.0) / 1000.0, &mut f);
1205 let next = g.value(2).unwrap();
1206 assert!((at_once - before).abs() < 15.0, "{before} {at_once}");
1207 assert!(next < before, "{before} {at_once} {next}");
1208 assert!(f.iter().any(|f| f.animation == 10 && !f.finished), "{f:?}");
1209 for _ in 0..100 {
1210 now += 10.0;
1211 g.tick(now / 1000.0, &mut f);
1212 }
1213 assert_eq!(g.value(2), Some(100.0));
1214 assert!(f.iter().any(|f| f.animation == 11 && f.finished), "{f:?}");
1215 }
1216
1217 #[test]
1218 fn a_reduced_motion_lands_at_its_end() {
1219 let spec = MotionPreset::FadeInUp.spec();
1220 let nodes = [2, 4, 6, 8, 10, 12, 14, 16, 18];
1221 let Composite::Parallel { children, .. } = spec.composite(&nodes, true) else {
1222 panic!()
1223 };
1224 assert_eq!(children.len(), 2);
1225 for child in &children {
1226 assert!(matches!(
1227 child,
1228 Composite::Run {
1229 driver: Driver::Timing {
1230 duration_ms: 0.0,
1231 ..
1232 },
1233 ..
1234 }
1235 ));
1236 }
1237 let starts: Vec<_> = spec.start_values().collect();
1238 assert_eq!(
1239 starts,
1240 [
1241 (MotionChannel::Opacity, 0.0),
1242 (MotionChannel::TranslateY, 24.0)
1243 ]
1244 );
1245 }
1246}