1pub use sui_animation::*;
2
3use sui_core::{InvalidationKind, InvalidationRequest, InvalidationTarget};
4use sui_runtime::{AnimateCtx, EventCtx, FrameClock, Motion, motion_policy};
5
6#[derive(Debug, Clone, PartialEq)]
7pub struct AnimationBindingInvalidation {
8 pub binding: AnimationBinding,
9 pub kind: InvalidationKind,
10}
11
12#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct TimelineTick<'a> {
14 pub samples: &'a [SampledAnimationValue],
15 pub invalidations: &'a [AnimationBindingInvalidation],
16 pub passed_markers: &'a [TimelineMarker],
18 pub should_continue: bool,
19}
20
21impl TimelineTick<'_> {
22 pub fn request_current_widget_invalidations(&self, ctx: &mut EventCtx) {
23 for invalidation in self.invalidations {
24 request_invalidation_kind(ctx, invalidation.kind);
25 }
26 if self.should_continue {
27 ctx.request_animation_frame();
28 }
29 }
30}
31
32pub(crate) trait StateMotion {
35 fn start(&mut self, target: f32, spec: AnimationSpec, ctx: &mut EventCtx) -> bool;
36}
37
38impl StateMotion for Progress {
39 fn start(&mut self, target: f32, spec: AnimationSpec, ctx: &mut EventCtx) -> bool {
40 self.animate(target, spec, ctx)
41 }
42}
43
44impl StateMotion for MotionScalar {
45 fn start(&mut self, target: f32, spec: AnimationSpec, ctx: &mut EventCtx) -> bool {
46 self.set_target_event_with(target, spec, ctx)
47 }
48}
49
50pub(crate) const ENTRANCE_SCALE: f32 = 0.96;
52
53pub(crate) fn entrance_scale(progress: f32) -> f32 {
56 1.0 - (1.0 - ENTRANCE_SCALE) * motion_policy().entrance_offset(progress)
57}
58
59pub trait TimelineBindingSink {
60 fn apply_animation_value(&mut self, binding: &AnimationBinding, value: AnimationValue) -> bool;
61}
62
63#[derive(Debug, Clone, Copy, PartialEq)]
72pub struct Progress {
73 motion: Motion<f32>,
74}
75
76impl Progress {
77 pub const EPSILON: f32 = 1e-4;
78
79 pub const fn new(value: f32) -> Self {
80 Self {
81 motion: Motion::new(value),
82 }
83 }
84
85 pub const fn movement(mut self) -> Self {
88 self.motion = self.motion.movement();
89 self
90 }
91
92 pub const fn invalidating(mut self, kind: InvalidationKind) -> Self {
95 self.motion = self.motion.invalidating(kind);
96 self
97 }
98
99 pub fn get(&self, clock: &impl FrameClock) -> f32 {
101 self.motion.get(clock)
102 }
103
104 pub fn at(&self, time: f64) -> f32 {
106 self.motion.at(time)
107 }
108
109 pub fn target(&self) -> f32 {
110 self.motion.target()
111 }
112
113 pub fn is_animating(&self, clock: &impl FrameClock) -> bool {
114 self.motion.is_animating(clock)
115 }
116
117 pub fn is_presented(&self, clock: &impl FrameClock) -> bool {
120 self.get(clock) > Self::EPSILON || self.target() > Self::EPSILON || self.is_animating(clock)
121 }
122
123 pub fn animate(&mut self, target: f32, spec: AnimationSpec, ctx: &mut impl AnimateCtx) -> bool {
126 ctx.animate(&mut self.motion, target.clamp(0.0, 1.0), spec)
127 }
128
129 pub fn animate_after(
131 &mut self,
132 target: f32,
133 delay: f64,
134 spec: AnimationSpec,
135 ctx: &mut impl AnimateCtx,
136 ) -> bool {
137 ctx.animate_after(&mut self.motion, target.clamp(0.0, 1.0), delay, spec)
138 }
139
140 pub fn jump_to(&mut self, value: f32) {
142 self.motion.jump_to(value.clamp(0.0, 1.0));
143 }
144
145 pub fn end_time(&self) -> Option<f64> {
147 self.motion.end_time()
148 }
149
150 pub(crate) fn animate_for(
154 &mut self,
155 target: f32,
156 spec: AnimationSpec,
157 ctx: &mut EventCtx,
158 widget: sui_core::WidgetId,
159 ) -> bool {
160 let target = target.clamp(0.0, 1.0);
161 let kind = self.motion.invalidation();
162 let before = self.motion.target();
163 let until = self.motion.start(target, ctx.current_time(), spec);
164 if before != target {
165 ctx.request(InvalidationRequest::new(
166 InvalidationTarget::Widget(widget),
167 kind,
168 ));
169 }
170 if let Some(until) = until {
171 ctx.track_motion_for(widget, until, kind);
172 }
173 until.is_some()
174 }
175}
176
177#[derive(Debug, Clone, Copy, PartialEq)]
185pub(crate) struct Reveal {
186 motion: Motion<f32>,
187 presented: bool,
188}
189
190impl Reveal {
191 pub(crate) const EPSILON: f32 = 1e-4;
192
193 pub(crate) const fn new(value: f32) -> Self {
194 Self {
195 motion: Motion::new(value).invalidating(InvalidationKind::Effect),
196 presented: value > Self::EPSILON,
197 }
198 }
199
200 pub(crate) fn get(&self, clock: &impl FrameClock) -> f32 {
202 self.motion.get(clock)
203 }
204
205 pub(crate) fn at(&self, time: f64) -> f32 {
207 self.motion.at(time)
208 }
209
210 pub(crate) fn target(&self) -> f32 {
211 self.motion.target()
212 }
213
214 pub(crate) fn is_presented(&self) -> bool {
217 self.presented
218 }
219
220 pub(crate) fn start(&mut self, target: f32, time: f64, spec: AnimationSpec) -> Option<f64> {
223 let target = target.clamp(0.0, 1.0);
224 let until = self.motion.start(target, time, spec);
225 if target > Self::EPSILON {
226 self.presented = true;
227 } else if until.is_none() {
228 self.presented = false;
229 }
230 until
231 }
232
233 pub(crate) fn jump_to(&mut self, value: f32) {
235 self.motion.jump_to(value.clamp(0.0, 1.0));
236 self.presented = value > Self::EPSILON;
237 }
238
239 pub(crate) fn settle(&mut self, time: f64) -> bool {
242 let presented = self.target() > Self::EPSILON
243 || self.motion.is_animating(&time)
244 || self.motion.at(time) > Self::EPSILON;
245 let changed = presented != self.presented;
246 self.presented = presented;
247 changed
248 }
249
250 pub(crate) const LAYER: [InvalidationKind; 2] =
252 [InvalidationKind::Effect, InvalidationKind::Transform];
253
254 pub(crate) fn track(
258 &self,
259 ctx: &mut EventCtx,
260 surfaces: &[sui_core::WidgetId],
261 until: Option<f64>,
262 kinds: &[InvalidationKind],
263 ) {
264 for surface in surfaces {
265 for kind in kinds {
266 ctx.request(InvalidationRequest::new(
267 InvalidationTarget::Widget(*surface),
268 *kind,
269 ));
270 if let Some(until) = until {
271 ctx.track_motion_for(*surface, until, *kind);
272 }
273 }
274 }
275 if let Some(until) = until
276 && self.target() <= Self::EPSILON
277 {
278 ctx.track_motion_end(until, InvalidationKind::Measure);
279 }
280 }
281}
282
283#[derive(Debug, Clone, Copy, PartialEq)]
293pub struct MotionScalar {
294 pub value: f32,
295 pub target: f32,
296 motion: MotionValue<f32>,
297}
298
299impl MotionScalar {
300 pub const EPSILON: f32 = 1e-4;
301
302 pub const fn new(value: f32) -> Self {
303 Self {
304 value,
305 target: value,
306 motion: MotionValue::new(value),
307 }
308 }
309
310 pub fn current(&self, time: f64) -> f32 {
311 if self.motion.is_animating() {
312 self.motion.value(time)
313 } else {
314 self.value
315 }
316 }
317
318 pub fn is_animating(&self) -> bool {
319 self.motion.is_animating()
320 }
321
322 pub fn set_target(&mut self, target: f32, time: f64, duration: f64, easing: Easing) -> bool {
323 self.set_target_with(target, time, AnimationSpec::tween(duration, easing))
324 }
325
326 pub fn set_target_with(&mut self, target: f32, time: f64, spec: AnimationSpec) -> bool {
329 self.retarget(target, time, spec.with_policy(motion_policy()))
330 }
331
332 pub fn set_movement_target(
335 &mut self,
336 target: f32,
337 time: f64,
338 duration: f64,
339 easing: Easing,
340 ) -> bool {
341 let spec = AnimationSpec::tween(duration, easing).with_movement_policy(motion_policy());
342 self.retarget(target, time, spec)
343 }
344
345 fn retarget(&mut self, target: f32, time: f64, spec: AnimationSpec) -> bool {
346 let target = target.clamp(0.0, 1.0);
347 let current = self.current(time);
348 if (current - target).abs() < Self::EPSILON {
349 self.value = target;
350 self.target = target;
351 self.motion.jump_to(target);
352 return false;
353 }
354
355 self.target = target;
356 let animating = self.motion.animate_to(target, time, spec);
357 self.value = if animating { current } else { target };
358 animating
359 }
360
361 pub fn set_target_event(
362 &mut self,
363 target: f32,
364 duration: f64,
365 easing: Easing,
366 ctx: &mut EventCtx,
367 ) -> bool {
368 self.set_target_event_with(target, AnimationSpec::tween(duration, easing), ctx)
369 }
370
371 pub fn set_target_event_with(
374 &mut self,
375 target: f32,
376 spec: AnimationSpec,
377 ctx: &mut EventCtx,
378 ) -> bool {
379 let should_animate = self.set_target_with(target, ctx.current_time(), spec);
380 if should_animate {
381 ctx.request_animation_frame();
382 }
383 should_animate
384 }
385
386 pub fn set_movement_target_event(
389 &mut self,
390 target: f32,
391 duration: f64,
392 easing: Easing,
393 ctx: &mut EventCtx,
394 ) -> bool {
395 let should_animate = self.set_movement_target(target, ctx.current_time(), duration, easing);
396 if should_animate {
397 ctx.request_animation_frame();
398 }
399 should_animate
400 }
401
402 pub fn advance(&mut self, time: f64) -> bool {
403 if !self.motion.is_animating() {
404 return false;
405 }
406
407 let animating = self.motion.advance(time);
408 self.value = if animating {
409 self.motion.value(time)
410 } else {
411 self.target
412 };
413 animating
414 }
415
416 pub fn changed_since(&self, previous: f32) -> bool {
417 (self.value - previous).abs() > Self::EPSILON
418 }
419
420 pub fn is_presented(&self) -> bool {
421 self.value > Self::EPSILON || self.target > Self::EPSILON || self.motion.is_animating()
422 }
423}
424
425#[derive(Debug, Clone, PartialEq)]
426pub struct TimelinePlayer {
427 timeline: Timeline,
428 compiled: CompiledTimeline,
429 compiled_dirty: bool,
430 playback: PlaybackState,
431 samples: SampleBuffer,
432 invalidations: Vec<AnimationBindingInvalidation>,
433 passed_markers: Vec<TimelineMarker>,
434}
435
436impl TimelinePlayer {
437 pub fn new(timeline: Timeline) -> Self {
438 let compiled = timeline.compile();
439 let sample_capacity = compiled.sample_capacity();
440 Self {
441 timeline,
442 compiled,
443 compiled_dirty: false,
444 playback: PlaybackState::default(),
445 samples: SampleBuffer::with_capacity(sample_capacity),
446 invalidations: Vec::with_capacity(sample_capacity),
447 passed_markers: Vec::new(),
448 }
449 }
450
451 pub fn timeline(&self) -> &Timeline {
452 &self.timeline
453 }
454
455 pub fn timeline_mut(&mut self) -> &mut Timeline {
456 self.compiled_dirty = true;
457 &mut self.timeline
458 }
459
460 pub fn set_timeline(&mut self, timeline: Timeline) {
461 self.timeline = timeline;
462 self.recompile_timeline();
463 }
464
465 pub fn playback(&self) -> PlaybackState {
466 self.playback
467 }
468
469 pub fn playback_mut(&mut self) -> &mut PlaybackState {
470 &mut self.playback
471 }
472
473 pub fn play(&mut self) {
474 self.playback.play();
475 }
476
477 pub fn pause(&mut self) {
478 self.playback.pause();
479 }
480
481 pub fn stop(&mut self) {
482 self.playback.stop();
483 }
484
485 pub fn seek(&mut self, time: f64) {
486 self.playback.seek(time, self.timeline.duration);
487 }
488
489 pub fn sample(&self) -> Vec<SampledAnimationValue> {
490 self.timeline.sample(self.playback.playhead)
491 }
492
493 pub fn sample_reusing_scratch(&mut self) -> &[SampledAnimationValue] {
494 self.ensure_compiled_timeline();
495 self.compiled
496 .sample_into(self.playback.playhead, &mut self.samples);
497 self.samples.samples()
498 }
499
500 pub fn tick<S>(&mut self, delta_seconds: f64, sink: &mut S) -> TimelineTick<'_>
501 where
502 S: TimelineBindingSink,
503 {
504 self.ensure_compiled_timeline();
505 let compiled = &self.compiled;
506 let passed_markers = &mut self.passed_markers;
507 passed_markers.clear();
508 self.playback
509 .tick_spans(delta_seconds, compiled.duration(), |span| {
510 compiled.markers_in(span, passed_markers);
511 });
512 self.compiled
513 .sample_into(self.playback.playhead, &mut self.samples);
514 self.invalidations.clear();
515 self.invalidations
516 .reserve(self.samples.len().saturating_sub(self.invalidations.len()));
517
518 for sample in self.samples.samples() {
519 if sink.apply_animation_value(&sample.binding, sample.value) {
520 self.invalidations.push(AnimationBindingInvalidation {
521 binding: sample.binding.clone(),
522 kind: invalidation_for_animation_property(&sample.binding.property),
523 });
524 }
525 }
526
527 TimelineTick {
528 samples: self.samples.samples(),
529 invalidations: &self.invalidations,
530 passed_markers: &self.passed_markers,
531 should_continue: self.playback.playing,
532 }
533 }
534
535 pub fn tick_event<S>(
536 &mut self,
537 delta_seconds: f64,
538 sink: &mut S,
539 ctx: &mut EventCtx,
540 ) -> TimelineTick<'_>
541 where
542 S: TimelineBindingSink,
543 {
544 let tick = self.tick(delta_seconds, sink);
545 tick.request_current_widget_invalidations(ctx);
546 tick
547 }
548
549 fn ensure_compiled_timeline(&mut self) {
550 if self.compiled_dirty {
551 self.recompile_timeline();
552 }
553 }
554
555 fn recompile_timeline(&mut self) {
556 self.compiled = self.timeline.compile();
557 self.compiled_dirty = false;
558 let sample_capacity = self.compiled.sample_capacity();
559 self.samples.reserve_capacity(sample_capacity);
560 self.invalidations
561 .reserve(sample_capacity.saturating_sub(self.invalidations.len()));
562 }
563}
564
565pub fn invalidation_for_animation_property(property: &AnimationProperty) -> InvalidationKind {
566 match property {
567 AnimationProperty::LayerOpacity => InvalidationKind::Effect,
568 AnimationProperty::LayerTranslation => InvalidationKind::Transform,
569 AnimationProperty::Bounds => InvalidationKind::Measure,
570 AnimationProperty::FillColor | AnimationProperty::Custom(_) => InvalidationKind::Paint,
571 }
572}
573
574fn request_invalidation_kind(ctx: &mut EventCtx, kind: InvalidationKind) {
575 match kind {
576 InvalidationKind::Measure => ctx.request_measure(),
577 InvalidationKind::Arrange => ctx.request_arrange(),
578 InvalidationKind::Ordering => ctx.request_ordering(),
579 InvalidationKind::Transform => ctx.request_transform(),
580 InvalidationKind::Clip => ctx.request(InvalidationRequest::new(
581 InvalidationTarget::Widget(ctx.widget_id()),
582 InvalidationKind::Clip,
583 )),
584 InvalidationKind::Effect => ctx.request_effect(),
585 InvalidationKind::Visibility => ctx.request_visibility(),
586 InvalidationKind::Paint => ctx.request_paint(),
587 InvalidationKind::HitTest => ctx.request_hit_test(),
588 InvalidationKind::Text => ctx.request_text(),
589 InvalidationKind::Semantics => ctx.request_semantics(),
590 InvalidationKind::Resources => ctx.request_resources(),
591 }
592}
593
594#[cfg(test)]
595mod tests {
596 use super::{
597 AnimationBinding, AnimationProperty, AnimationSpec, AnimationTargetId, AnimationValue,
598 Clip, Easing, Keyframe, MotionScalar, Timeline, TimelineBindingSink, TimelinePlayer, Track,
599 invalidation_for_animation_property,
600 };
601 use sui_core::{Color, InvalidationKind, MotionPreference, Vector};
602
603 #[derive(Default)]
604 struct DemoSink {
605 opacity: f32,
606 translation: Vector,
607 fill: Color,
608 }
609
610 impl TimelineBindingSink for DemoSink {
611 fn apply_animation_value(
612 &mut self,
613 binding: &AnimationBinding,
614 value: AnimationValue,
615 ) -> bool {
616 match (&binding.property, value) {
617 (AnimationProperty::LayerOpacity, AnimationValue::Scalar(value)) => {
618 let changed = (self.opacity - value).abs() > f32::EPSILON;
619 self.opacity = value;
620 changed
621 }
622 (AnimationProperty::LayerTranslation, AnimationValue::Vector(value)) => {
623 let changed = self.translation != value;
624 self.translation = value;
625 changed
626 }
627 (AnimationProperty::FillColor, AnimationValue::Color(value)) => {
628 let changed = self.fill != value;
629 self.fill = value;
630 changed
631 }
632 _ => false,
633 }
634 }
635 }
636
637 fn binding(property: AnimationProperty) -> AnimationBinding {
638 AnimationBinding::new(AnimationTargetId::new("preview"), property)
639 }
640
641 struct ResetMotion;
643
644 impl Drop for ResetMotion {
645 fn drop(&mut self) {
646 sui_runtime::reset_motion_settings();
647 }
648 }
649
650 #[test]
651 fn motion_scalar_follows_the_time_scale_and_motion_off() {
652 let _reset = ResetMotion;
653 sui_runtime::set_motion_time_scale(0.5);
654 let mut slow = MotionScalar::new(0.0);
655 assert!(slow.set_target(1.0, 0.0, 0.2, Easing::Linear));
656 assert!(slow.advance(0.2));
657 assert!((slow.value - 0.5).abs() < 1e-5);
658 assert!(!slow.advance(0.4));
659 assert_eq!(slow.value, 1.0);
660
661 sui_runtime::set_app_motion_preference(Some(MotionPreference::Off));
662 let mut instant = MotionScalar::new(0.0);
663 assert!(!instant.set_target(1.0, 0.0, 0.2, Easing::Linear));
664 assert_eq!(instant.value, 1.0);
665 assert!(!instant.is_animating());
666 }
667
668 #[test]
669 fn movement_jumps_but_fades_still_play_under_reduced_motion() {
670 let _reset = ResetMotion;
671 sui_runtime::set_app_motion_preference(Some(MotionPreference::Reduced));
672
673 let mut indicator = MotionScalar::new(0.0);
674 assert!(!indicator.set_movement_target(1.0, 0.0, 0.2, Easing::Linear));
675 assert_eq!(indicator.value, 1.0);
676
677 let mut fade = MotionScalar::new(0.0);
678 assert!(fade.set_target(1.0, 0.0, 0.2, Easing::Linear));
679 assert!(fade.advance(0.1));
680 assert!((fade.value - 0.5).abs() < 1e-5);
681 }
682
683 #[test]
684 fn motion_scalar_turns_around_without_stopping() {
685 let _reset = ResetMotion;
686 let mut hover = MotionScalar::new(0.0);
687 hover.set_target(1.0, 0.0, 0.2, Easing::EaseInOut);
688 hover.advance(0.1);
689 let rising = hover.value;
690
691 assert!(hover.set_target(0.0, 0.1, 0.2, Easing::EaseInOut));
694 hover.advance(0.12);
695 assert!(hover.value > rising);
696 assert!(!hover.advance(0.3));
697 assert_eq!(hover.value, 0.0);
698 }
699
700 #[test]
701 fn theme_motion_specs_match_their_tokens() {
702 let motion = crate::theme::ThemeMotion::standard();
703
704 assert_eq!(
705 motion.hover_spec(),
706 AnimationSpec::tween(motion.hover_duration(), motion.hover_easing())
707 );
708 assert_eq!(
709 motion.entrance_spec().duration(),
710 motion.entrance_duration()
711 );
712 }
713
714 #[test]
715 fn animation_property_maps_to_retained_invalidation_kinds() {
716 assert_eq!(
717 invalidation_for_animation_property(&AnimationProperty::LayerOpacity),
718 InvalidationKind::Effect
719 );
720 assert_eq!(
721 invalidation_for_animation_property(&AnimationProperty::LayerTranslation),
722 InvalidationKind::Transform
723 );
724 assert_eq!(
725 invalidation_for_animation_property(&AnimationProperty::FillColor),
726 InvalidationKind::Paint
727 );
728 }
729
730 #[test]
731 fn timeline_player_applies_samples_and_reports_invalidations() {
732 let timeline = Timeline::new(1.0).with_clip(
733 Clip::new("intro", 0.0, 1.0)
734 .with_track(
735 Track::new(binding(AnimationProperty::LayerOpacity)).with_keyframes([
736 Keyframe::new(0.0, AnimationValue::Scalar(0.0)).with_easing(Easing::Linear),
737 Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
738 ]),
739 )
740 .with_track(
741 Track::new(binding(AnimationProperty::LayerTranslation)).with_keyframes([
742 Keyframe::new(0.0, AnimationValue::Vector(Vector::ZERO))
743 .with_easing(Easing::Linear),
744 Keyframe::new(1.0, AnimationValue::Vector(Vector::new(10.0, 0.0))),
745 ]),
746 ),
747 );
748 let mut player = TimelinePlayer::new(timeline);
749 let mut sink = DemoSink::default();
750 player.play();
751
752 let tick = player.tick(0.5, &mut sink);
753
754 assert!(tick.should_continue);
755 assert_eq!(tick.samples.len(), 2);
756 assert_eq!(tick.invalidations.len(), 2);
757 assert!((sink.opacity - 0.5).abs() < 1e-6);
758 assert_eq!(sink.translation, Vector::new(5.0, 0.0));
759 }
760}