1#[cfg(not(target_family = "wasm"))]
2use std::time::Instant;
3use std::{rc::Rc, time::Duration};
4#[cfg(target_family = "wasm")]
5use web_time::Instant;
6
7use wgpui::{
8 App, Bounds, ElementId, Pixels, SharedString, Size, SpringConfig, SpringState, SpringTarget,
9 Window,
10};
11
12use crate::animation::{Lerp, ease_out_cubic};
13
14mod easing;
15mod keyframes;
16mod presence;
17mod reveal;
18mod sequence;
19mod stagger;
20mod timing;
21
22pub use easing::{Easing, EasingError, LinearStop, StepPosition};
23pub use keyframes::{Discrete, DiscreteError, Keyframe, KeyframeError, Keyframes};
24pub use presence::{Presence, PresencePhase, PresenceSample};
25pub use reveal::MotionReveal;
26pub use sequence::{Sequence, SequenceSample, SequenceStep};
27pub use stagger::{Stagger, StaggerOrigin};
28pub use timing::{
29 IterationCount, MotionPhase, PlaybackDirection, SignedDuration, Timing, TimingSample,
30};
31
32const DEFAULT_SPRING_EPSILON: f32 = 0.001;
34
35pub trait Interpolate: Clone {
37 fn interpolate(&self, target: &Self, progress: f32) -> Self;
38}
39
40impl<T: Lerp> Interpolate for T {
41 fn interpolate(&self, target: &Self, progress: f32) -> Self {
42 self.lerp(target, progress)
43 }
44}
45
46impl Interpolate for Size<Pixels> {
47 fn interpolate(&self, target: &Self, progress: f32) -> Self {
48 Size::new(
49 self.width.lerp(&target.width, progress),
50 self.height.lerp(&target.height, progress),
51 )
52 }
53}
54
55impl Interpolate for Bounds<Pixels> {
56 fn interpolate(&self, target: &Self, progress: f32) -> Self {
57 Bounds::new(
58 self.origin.lerp(&target.origin, progress),
59 self.size.interpolate(&target.size, progress),
60 )
61 }
62}
63
64#[derive(Clone, Copy, Debug, PartialEq)]
66pub struct MotionTransform {
67 pub translation: wgpui::Point<Pixels>,
68 pub scale: wgpui::Point<f32>,
69 pub rotation_radians: f32,
70 pub opacity: f32,
71}
72
73impl MotionTransform {
74 pub fn identity() -> Self {
75 Self {
76 translation: wgpui::point(wgpui::px(0.0), wgpui::px(0.0)),
77 scale: wgpui::point(1.0, 1.0),
78 rotation_radians: 0.0,
79 opacity: 1.0,
80 }
81 }
82}
83
84impl Default for MotionTransform {
85 fn default() -> Self {
86 Self::identity()
87 }
88}
89
90impl Interpolate for MotionTransform {
91 fn interpolate(&self, target: &Self, progress: f32) -> Self {
92 Self {
93 translation: self.translation.lerp(&target.translation, progress),
94 scale: wgpui::point(
95 self.scale.x.lerp(&target.scale.x, progress),
96 self.scale.y.lerp(&target.scale.y, progress),
97 ),
98 rotation_radians: self
99 .rotation_radians
100 .lerp(&target.rotation_radians, progress),
101 opacity: self.opacity.lerp(&target.opacity, progress),
102 }
103 }
104}
105
106#[derive(Clone)]
112pub struct Transition {
113 duration: Duration,
114 delay: SignedDuration,
115 easing: Easing,
116}
117
118impl Transition {
119 pub fn new(duration: Duration) -> Self {
120 Self {
121 duration,
122 delay: SignedDuration::ZERO,
123 easing: Easing::Custom(Rc::new(ease_out_cubic)),
124 }
125 }
126
127 pub fn delay(mut self, delay: impl Into<SignedDuration>) -> Self {
128 self.delay = delay.into();
129 self
130 }
131
132 pub fn ease(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
133 self.easing = Easing::Custom(Rc::new(easing));
134 self
135 }
136
137 pub fn easing(mut self, easing: Easing) -> Self {
138 self.easing = easing;
139 self
140 }
141
142 fn sample(&self, progress: f32) -> f32 {
143 self.easing.sample(progress)
144 }
145
146 pub(crate) fn curve(&self) -> &Easing {
149 &self.easing
150 }
151
152 fn progress(&self, elapsed: Duration, duration: Duration) -> (f32, MotionStatus) {
153 let Some(active_elapsed) = self.delay.active_elapsed(elapsed) else {
154 return (0.0, MotionStatus::Delayed);
155 };
156 if duration.is_zero() || active_elapsed >= duration {
157 return (1.0, MotionStatus::Finished);
158 }
159 (
160 active_elapsed.as_secs_f32() / duration.as_secs_f32(),
161 MotionStatus::Running,
162 )
163 }
164
165 fn finishes_after(&self) -> Duration {
168 match self.delay {
169 SignedDuration::Positive(delay) => delay.saturating_add(self.duration),
170 SignedDuration::Negative(delay) => self.duration.saturating_sub(delay),
171 }
172 }
173}
174
175impl From<Duration> for SignedDuration {
176 fn from(duration: Duration) -> Self {
177 Self::positive(duration)
178 }
179}
180
181#[derive(Clone, Debug, Eq, Hash, PartialEq)]
183pub struct TransitionId(ElementId);
184
185impl From<ElementId> for TransitionId {
186 fn from(id: ElementId) -> Self {
187 Self(id)
188 }
189}
190
191impl From<&'static str> for TransitionId {
192 fn from(id: &'static str) -> Self {
193 Self(id.into())
194 }
195}
196
197impl From<String> for TransitionId {
198 fn from(id: String) -> Self {
199 Self(id.into())
200 }
201}
202
203impl From<SharedString> for TransitionId {
204 fn from(id: SharedString) -> Self {
205 Self(id.into())
206 }
207}
208
209impl From<usize> for TransitionId {
210 fn from(id: usize) -> Self {
211 Self(id.into())
212 }
213}
214
215impl From<i32> for TransitionId {
216 fn from(id: i32) -> Self {
217 Self(id.into())
218 }
219}
220
221impl From<TransitionId> for ElementId {
222 fn from(id: TransitionId) -> Self {
223 ElementId::NamedChild(id.0.into(), "__base-transition-state".into())
224 }
225}
226
227impl<I, C> From<(I, C)> for TransitionId
228where
229 I: Into<ElementId>,
230 C: Into<SharedString>,
231{
232 fn from((id, channel): (I, C)) -> Self {
233 Self(ElementId::NamedChild(id.into().into(), channel.into()))
234 }
235}
236
237#[derive(Clone)]
238struct ValueTransition<T> {
239 from: T,
240 target: T,
241 started_at: Instant,
242 reversing_factor: f32,
243 duration: Duration,
244}
245
246#[derive(Clone, Copy, Debug, Eq, PartialEq)]
247pub enum MotionStatus {
248 Idle,
249 Delayed,
250 Running,
251 Finished,
252}
253
254#[derive(Clone, Copy, Debug, PartialEq)]
255pub struct MotionValue<T> {
256 pub value: T,
257 pub status: MotionStatus,
258}
259
260pub fn transition<T>(
269 id: impl Into<TransitionId>,
270 target: T,
271 policy: Transition,
272 window: &mut Window,
273 cx: &mut App,
274) -> T
275where
276 T: Interpolate + PartialEq + 'static,
277{
278 transition_with_status(id, target, policy, window, cx).value
279}
280
281pub fn transition_with_status<T>(
282 id: impl Into<TransitionId>,
283 target: T,
284 policy: Transition,
285 window: &mut Window,
286 cx: &mut App,
287) -> MotionValue<T>
288where
289 T: Interpolate + PartialEq + 'static,
290{
291 let id: ElementId = id.into().into();
292 let now = cx.background_executor().now();
293 let state = window.use_keyed_state(id, cx, |_, _| ValueTransition {
294 from: target.clone(),
295 target: target.clone(),
296 started_at: now,
297 reversing_factor: 1.0,
298 duration: policy.duration,
299 });
300
301 let snapshot = state.read(cx).clone();
302
303 if cx.reduce_motion() || policy.duration.is_zero() {
304 if snapshot.from != target || snapshot.target != target {
305 state.update(cx, |state, _| {
306 state.from = target.clone();
307 state.target = target.clone();
308 state.started_at = now;
309 state.reversing_factor = 1.0;
310 state.duration = policy.duration;
311 });
312 }
313 return MotionValue {
314 value: target,
315 status: MotionStatus::Finished,
316 };
317 }
318
319 let elapsed = now.saturating_duration_since(snapshot.started_at);
320 let (progress, status) = policy.progress(elapsed, snapshot.duration);
321 let sampled = snapshot
322 .from
323 .interpolate(&snapshot.target, policy.sample(progress));
324
325 let (value, status) = if snapshot.target != target {
326 let reversing = target == snapshot.from;
327 let reversing_factor = if reversing {
328 (policy.sample(progress) * snapshot.reversing_factor
329 + (1.0 - snapshot.reversing_factor))
330 .clamp(0.0, 1.0)
331 } else {
332 1.0
333 };
334 let duration = policy.duration.mul_f64(f64::from(reversing_factor));
336 state.update(cx, |state, _| {
337 state.from = sampled.clone();
338 state.target = target.clone();
339 state.started_at = now;
340 state.reversing_factor = reversing_factor;
341 state.duration = duration;
342 });
343 let (initial_progress, initial_status) = policy.progress(Duration::ZERO, duration);
344 (
345 sampled.interpolate(&target, policy.sample(initial_progress)),
346 initial_status,
347 )
348 } else {
349 (
350 sampled,
351 if snapshot.from == snapshot.target {
352 MotionStatus::Idle
353 } else {
354 status
355 },
356 )
357 };
358 if matches!(status, MotionStatus::Delayed | MotionStatus::Running) {
359 window.request_animation_frame();
360 }
361 MotionValue { value, status }
362}
363
364#[derive(Clone, Copy)]
365struct KeyframePlayback {
366 started_at: Instant,
367}
368
369pub fn animate_keyframes<T>(
376 id: impl Into<TransitionId>,
377 keyframes: &Keyframes<T>,
378 timing: Timing,
379 window: &mut Window,
380 cx: &mut App,
381) -> MotionValue<T>
382where
383 T: Interpolate + 'static,
384{
385 let id: TransitionId = id.into();
386 let id = ElementId::NamedChild(ElementId::from(id).into(), "__keyframes".into());
387 let now = cx.background_executor().now();
388 let state = window.use_keyed_state(id, cx, |_, _| KeyframePlayback { started_at: now });
389 let started_at = state.read(cx).started_at;
390
391 if cx.reduce_motion() {
392 return MotionValue {
393 value: keyframes.sample(1.0),
394 status: MotionStatus::Finished,
395 };
396 }
397
398 let sample = timing.sample(now.saturating_duration_since(started_at));
399 let status = match sample.phase {
400 MotionPhase::Before => MotionStatus::Delayed,
401 MotionPhase::Active => MotionStatus::Running,
402 MotionPhase::After => MotionStatus::Finished,
403 };
404 if matches!(status, MotionStatus::Delayed | MotionStatus::Running) {
405 window.request_animation_frame();
406 }
407 MotionValue {
408 value: keyframes.sample(sample.directed_progress),
409 status,
410 }
411}
412
413#[derive(Clone, Copy, Debug)]
422pub struct Spring {
423 response: Duration,
424 damping: f32,
425 epsilon: f32,
426 travel: bool,
427}
428
429#[derive(Clone, Copy, Debug, Eq, PartialEq)]
431pub enum SpringError {
432 InvalidDamping,
433 InvalidEpsilon,
434}
435
436impl std::fmt::Display for SpringError {
437 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
438 match self {
439 Self::InvalidDamping => f.write_str("spring damping must be finite and non-negative"),
440 Self::InvalidEpsilon => {
441 f.write_str("spring epsilon must be finite and greater than zero")
442 }
443 }
444 }
445}
446
447impl std::error::Error for SpringError {}
448
449impl Spring {
450 pub const fn new(response: Duration) -> Self {
465 Self {
466 response,
467 damping: 1.0,
468 epsilon: DEFAULT_SPRING_EPSILON,
469 travel: true,
470 }
471 }
472
473 pub const fn with_damping(self, ratio: f32) -> Self {
488 match self.try_with_damping(ratio) {
489 Ok(spring) => spring,
490 Err(_) => panic!("spring damping must be finite and non-negative"),
491 }
492 }
493
494 pub const fn try_with_damping(mut self, ratio: f32) -> Result<Self, SpringError> {
496 if !ratio.is_finite() || ratio < 0.0 {
497 return Err(SpringError::InvalidDamping);
498 }
499 self.damping = ratio;
500 Ok(self)
501 }
502
503 pub const fn with_travel(mut self, travel: bool) -> Self {
516 self.travel = travel;
517 self
518 }
519
520 pub const fn with_epsilon(self, epsilon: f32) -> Self {
532 match self.try_with_epsilon(epsilon) {
533 Ok(spring) => spring,
534 Err(_) => panic!("spring epsilon must be finite and greater than zero"),
535 }
536 }
537
538 pub const fn try_with_epsilon(mut self, epsilon: f32) -> Result<Self, SpringError> {
540 if !epsilon.is_finite() || epsilon <= 0.0 {
541 return Err(SpringError::InvalidEpsilon);
542 }
543 self.epsilon = epsilon;
544 Ok(self)
545 }
546
547 pub const fn epsilon(self) -> f32 {
549 self.epsilon
550 }
551
552 fn config(&self) -> SpringConfig {
559 let frequency = std::f32::consts::TAU / self.response.as_secs_f32();
560 SpringConfig::new(frequency * frequency, 2.0 * self.damping * frequency, 1.0)
561 }
562}
563
564#[derive(Clone, Copy)]
565struct SpringTransition {
566 state: SpringState,
567 target: f32,
568 updated_at: Instant,
569}
570
571pub fn spring<T>(
581 id: impl Into<TransitionId>,
582 target: T,
583 policy: Spring,
584 window: &mut Window,
585 cx: &mut App,
586) -> T::Output
587where
588 T: SpringTarget,
589{
590 let id: ElementId = id.into().into();
591 let now = cx.background_executor().now();
592 let target_position = target.target();
593 let state = window.use_keyed_state(id, cx, |_, _| SpringTransition {
594 state: SpringState {
595 position: target_position,
596 velocity: 0.0,
597 },
598 target: target_position,
599 updated_at: now,
600 });
601
602 let snapshot = *state.read(cx);
603 let at_rest_on_target =
604 snapshot.state.position == target_position && snapshot.state.velocity == 0.0;
605
606 if at_rest_on_target {
617 return target.resolve(target_position);
618 }
619
620 let settle = |state: &mut SpringTransition| {
621 state.state = SpringState {
622 position: target_position,
623 velocity: 0.0,
624 };
625 state.target = target_position;
626 state.updated_at = now;
627 };
628
629 if cx.reduce_motion() || !policy.travel || policy.response.is_zero() {
630 state.update(cx, |state, _| settle(state));
631 return target.resolve(target_position);
632 }
633
634 let elapsed = now
637 .saturating_duration_since(snapshot.updated_at)
638 .as_secs_f32();
639 let config = policy.config();
640 let stepped = config.step(snapshot.state, snapshot.target, elapsed);
641
642 if config.is_settled(stepped, target_position, policy.epsilon) {
643 state.update(cx, |state, _| settle(state));
644 return target.resolve(target_position);
645 }
646
647 state.update(cx, |state, _| {
648 state.state = stepped;
649 state.target = target_position;
650 state.updated_at = now;
651 });
652 window.request_animation_frame();
653 target.resolve(stepped.position)
654}
655
656#[cfg(test)]
657mod css_timing_tests {
658 use super::{
659 Easing, IterationCount, LinearStop, MotionPhase, PlaybackDirection, SignedDuration,
660 StepPosition, Timing,
661 };
662 use std::time::Duration;
663
664 #[test]
665 fn css_keyword_easing_matches_published_reference_samples() {
666 for (easing, samples) in [
667 (Easing::Ease, [(0.2, 0.295), (0.5, 0.802), (0.8, 0.976)]),
668 (Easing::EaseIn, [(0.2, 0.062), (0.5, 0.315), (0.8, 0.692)]),
669 (Easing::EaseOut, [(0.2, 0.308), (0.5, 0.685), (0.8, 0.938)]),
670 (Easing::EaseInOut, [(0.2, 0.082), (0.5, 0.5), (0.8, 0.918)]),
671 ] {
672 for (progress, expected) in samples {
673 let actual = easing.sample(progress);
674 assert!(
675 (actual - expected).abs() < 0.002,
676 "{easing:?}({progress}) = {actual}, expected {expected}"
677 );
678 }
679 }
680 }
681
682 #[test]
683 fn cubic_bezier_easing_keeps_anticipation_and_overshoot() {
684 let anticipate = Easing::cubic_bezier(1.0, -0.4, 0.35, 0.95).unwrap();
685 let overshoot = Easing::cubic_bezier(0.175, 0.885, 0.32, 1.275).unwrap();
686
687 assert!(anticipate.sample(0.2) < 0.0);
688 assert!(overshoot.sample(0.8) > 1.0);
689 for easing in [anticipate, overshoot] {
690 assert_eq!(easing.sample(-1.0), 0.0);
691 assert_eq!(easing.sample(2.0), 1.0);
692 }
693 }
694
695 #[test]
696 fn step_easing_observes_css_jump_positions() {
697 let start = Easing::steps(4, StepPosition::JumpStart).unwrap();
698 let end = Easing::steps(4, StepPosition::JumpEnd).unwrap();
699
700 assert_eq!(start.sample(0.0), 0.25);
701 assert_eq!(start.sample(0.24), 0.25);
702 assert_eq!(start.sample(0.25), 0.5);
703 assert_eq!(end.sample(0.0), 0.0);
704 assert_eq!(end.sample(0.24), 0.0);
705 assert_eq!(end.sample(0.25), 0.25);
706 assert!(Easing::steps(0, StepPosition::JumpEnd).is_err());
707
708 let none = Easing::steps(4, StepPosition::JumpNone).unwrap();
709 let both = Easing::steps(4, StepPosition::JumpBoth).unwrap();
710 assert_eq!(none.sample(0.0), 0.0);
711 assert!((none.sample(0.5) - 2.0 / 3.0).abs() < f32::EPSILON);
712 assert_eq!(none.sample(1.0), 1.0);
713 assert_eq!(both.sample(0.0), 0.2);
714 assert_eq!(both.sample(1.0), 1.0);
715 assert!(Easing::steps(1, StepPosition::JumpNone).is_err());
716 }
717
718 #[test]
719 fn linear_stops_fill_omitted_positions_before_sampling() {
720 let easing = Easing::linear_stops([
721 LinearStop::at(0.0, 0.0),
722 LinearStop::new(0.2),
723 LinearStop::new(0.8),
724 LinearStop::at(1.0, 1.0),
725 ])
726 .unwrap();
727
728 assert!((easing.sample(1.0 / 3.0) - 0.2).abs() < 1e-6);
729 assert!((easing.sample(0.5) - 0.5).abs() < 1e-6);
730 assert!(
731 Easing::linear_stops([LinearStop::at(0.0, 0.8), LinearStop::at(1.0, 0.2)]).is_err()
732 );
733 }
734
735 #[test]
736 fn negative_delay_starts_inside_the_active_interval() {
737 let timing = Timing::new(Duration::from_millis(100))
738 .delay(SignedDuration::negative(Duration::from_millis(25)));
739 let sample = timing.sample(Duration::ZERO);
740
741 assert_eq!(sample.phase, MotionPhase::Active);
742 assert!((sample.directed_progress - 0.25).abs() < f32::EPSILON);
743 assert!(sample.active);
744 assert!(!sample.finished);
745 }
746
747 #[test]
748 fn alternate_direction_reverses_odd_iterations() {
749 let timing = Timing::new(Duration::from_millis(100))
750 .iterations(IterationCount::Finite(2))
751 .direction(PlaybackDirection::Alternate)
752 .ease(Easing::Linear);
753
754 let first = timing.sample(Duration::from_millis(25));
755 let second = timing.sample(Duration::from_millis(125));
756 let finished = timing.sample(Duration::from_millis(200));
757
758 assert_eq!(first.iteration, 0);
759 assert_eq!(first.directed_progress, 0.25);
760 assert_eq!(second.iteration, 1);
761 assert_eq!(second.directed_progress, 0.75);
762 assert_eq!(finished.phase, MotionPhase::After);
763 assert_eq!(finished.directed_progress, 0.0);
764 assert!(finished.finished);
765 }
766}
767
768#[cfg(test)]
769mod motion_track_tests {
770 use super::{
771 Discrete, Easing, Interpolate as _, Keyframe, KeyframeError, Keyframes, MotionTransform,
772 Stagger, StaggerOrigin,
773 };
774 use std::time::Duration;
775 use wgpui::{Bounds, Point, Size, point, px, size};
776
777 #[test]
778 fn keyframes_validate_offsets_and_sample_each_segments_easing() {
779 assert!(matches!(
780 Keyframes::try_new([Keyframe::new(0.2, 0.0_f32), Keyframe::new(1.0, 1.0_f32),]),
781 Err(KeyframeError::MissingEndpoint)
782 ));
783 assert!(matches!(
784 Keyframes::try_new([
785 Keyframe::new(0.0, 0.0_f32),
786 Keyframe::new(0.8, 1.0_f32),
787 Keyframe::new(0.7, 2.0_f32),
788 Keyframe::new(1.0, 3.0_f32),
789 ]),
790 Err(KeyframeError::OffsetsNotMonotonic)
791 ));
792
793 let track = Keyframes::try_new([
794 Keyframe::new(0.0, 0.0_f32)
795 .ease(Easing::steps(2, super::StepPosition::JumpEnd).unwrap()),
796 Keyframe::new(0.5, 10.0_f32).ease(Easing::Linear),
797 Keyframe::new(1.0, 20.0_f32),
798 ])
799 .unwrap();
800
801 assert_eq!(track.sample(0.2), 0.0);
802 assert_eq!(track.sample(0.3), 5.0);
803 assert_eq!(track.sample(0.75), 15.0);
804 assert_eq!(track.sample(1.0), 20.0);
805 }
806
807 #[test]
808 fn discrete_values_switch_only_at_the_requested_progress() {
809 let value = Discrete::new("old", "new").switch_at(0.75).unwrap();
810 assert_eq!(value.sample(0.749), "old");
811 assert_eq!(value.sample(0.75), "new");
812 assert!(Discrete::new(0, 1).switch_at(f32::NAN).is_err());
813 }
814
815 #[test]
816 fn stagger_origins_produce_stable_delays_without_allocating_a_schedule() {
817 let interval = Duration::from_millis(20);
818 let first = Stagger::new(interval, StaggerOrigin::First);
819 let last = Stagger::new(interval, StaggerOrigin::Last);
820 let center = Stagger::new(interval, StaggerOrigin::Center);
821
822 assert_eq!(first.delay(3, 5), Duration::from_millis(60));
823 assert_eq!(last.delay(3, 5), Duration::from_millis(20));
824 assert_eq!(center.delay(2, 5), Duration::ZERO);
825 assert_eq!(center.delay(0, 5), Duration::from_millis(40));
826 assert_eq!(first.delay(7, 0), Duration::ZERO);
827 }
828
829 #[test]
830 fn common_gpui_geometry_interpolates_channel_by_channel() {
831 let from_size = size(px(10.0), px(20.0));
832 let to_size = size(px(30.0), px(60.0));
833 assert_eq!(
834 from_size.interpolate(&to_size, 0.25),
835 size(px(15.0), px(30.0))
836 );
837
838 let from = Bounds::new(point(px(0.0), px(10.0)), from_size);
839 let to = Bounds::new(point(px(40.0), px(50.0)), to_size);
840 assert_eq!(
841 from.interpolate(&to, 0.5),
842 Bounds::new(point(px(20.0), px(30.0)), size(px(20.0), px(40.0)))
843 );
844
845 let _: Point<wgpui::Pixels> = from.origin;
846 let _: Size<wgpui::Pixels> = from.size;
847
848 let transform = MotionTransform::identity().interpolate(
849 &MotionTransform {
850 translation: point(px(20.0), px(40.0)),
851 scale: point(2.0, 0.5),
852 rotation_radians: std::f32::consts::PI,
853 opacity: 0.0,
854 },
855 0.5,
856 );
857 assert_eq!(transform.translation, point(px(10.0), px(20.0)));
858 assert_eq!(transform.scale, point(1.5, 0.75));
859 assert_eq!(transform.rotation_radians, std::f32::consts::FRAC_PI_2);
860 assert_eq!(transform.opacity, 0.5);
861 }
862}
863
864#[cfg(test)]
865mod tests {
866 use std::{
867 cell::{Cell, RefCell},
868 rc::Rc,
869 time::Duration,
870 };
871
872 use wgpui::{Empty, IntoElement, Render, TestAppContext, WindowHandle, px, size};
873
874 use super::*;
875
876 struct StatusView {
877 target: Rc<Cell<f32>>,
878 policy: Transition,
879 samples: Rc<RefCell<Vec<MotionValue<f32>>>>,
880 }
881
882 impl Render for StatusView {
883 fn render(
884 &mut self,
885 window: &mut Window,
886 cx: &mut wgpui::Context<Self>,
887 ) -> impl IntoElement {
888 self.samples.borrow_mut().push(transition_with_status(
889 ("status-test", "value"),
890 self.target.get(),
891 self.policy.clone(),
892 window,
893 cx,
894 ));
895 Empty
896 }
897 }
898
899 struct StatusFixture {
900 window: WindowHandle<StatusView>,
901 target: Rc<Cell<f32>>,
902 samples: Rc<RefCell<Vec<MotionValue<f32>>>>,
903 }
904
905 impl StatusFixture {
906 fn open(cx: &mut TestAppContext, policy: Transition) -> Self {
907 let target = Rc::new(Cell::new(0.0));
908 let samples = Rc::new(RefCell::new(Vec::new()));
909 let window = cx.open_window(size(px(100.), px(100.)), {
910 let target = target.clone();
911 let samples = samples.clone();
912 move |_, _| StatusView {
913 target,
914 policy,
915 samples,
916 }
917 });
918 cx.run_until_parked();
919 Self {
920 window,
921 target,
922 samples,
923 }
924 }
925
926 fn render(&self, cx: &mut TestAppContext, target: f32) -> MotionValue<f32> {
927 self.target.set(target);
928 self.window
929 .update(cx, |_, window, _| window.refresh())
930 .unwrap();
931 cx.run_until_parked();
932 *self.samples.borrow().last().unwrap()
933 }
934 }
935
936 #[wgpui::test]
937 fn status_transition_reports_delay_running_and_finished(cx: &mut TestAppContext) {
938 let fixture = StatusFixture::open(
939 cx,
940 Transition::new(Duration::from_millis(100)).delay(Duration::from_millis(20)),
941 );
942 assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Delayed);
943
944 cx.executor().advance_clock(Duration::from_millis(20));
945 assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Running);
946 cx.executor().advance_clock(Duration::from_millis(100));
947 assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Finished);
948 }
949
950 #[wgpui::test]
951 fn negative_delay_samples_a_target_change_inside_its_interval(cx: &mut TestAppContext) {
952 let fixture = StatusFixture::open(
953 cx,
954 Transition::new(Duration::from_millis(100))
955 .delay(SignedDuration::negative(Duration::from_millis(25)))
956 .ease(|t| t),
957 );
958 let sample = fixture.render(cx, 1.0);
959 assert_eq!(sample.status, MotionStatus::Running);
960 assert_eq!(sample.value, 0.25);
961 }
962
963 #[wgpui::test]
964 fn a_direct_reversal_shortens_the_return_transition(cx: &mut TestAppContext) {
965 let fixture =
966 StatusFixture::open(cx, Transition::new(Duration::from_millis(100)).ease(|t| t));
967 assert_eq!(fixture.render(cx, 1.0).value, 0.0);
968 cx.executor().advance_clock(Duration::from_millis(50));
969 assert_eq!(fixture.render(cx, 0.0).value, 0.5);
970 cx.executor().advance_clock(Duration::from_millis(25));
971 assert_eq!(fixture.render(cx, 0.0).value, 0.25);
972 }
973
974 struct KeyframeView {
975 track: Keyframes<f32>,
976 timing: Timing,
977 samples: Rc<RefCell<Vec<MotionValue<f32>>>>,
978 }
979
980 impl Render for KeyframeView {
981 fn render(
982 &mut self,
983 window: &mut Window,
984 cx: &mut wgpui::Context<Self>,
985 ) -> impl IntoElement {
986 self.samples.borrow_mut().push(animate_keyframes(
987 "keyframe-test",
988 &self.track,
989 self.timing.clone(),
990 window,
991 cx,
992 ));
993 Empty
994 }
995 }
996
997 #[wgpui::test]
998 fn keyed_keyframes_follow_timing_and_stop_after_completion(cx: &mut TestAppContext) {
999 let samples = Rc::new(RefCell::new(Vec::new()));
1000 let window = cx.open_window(size(px(100.), px(100.)), {
1001 let samples = samples.clone();
1002 move |_, _| KeyframeView {
1003 track: Keyframes::try_new([Keyframe::new(0.0, 0.0), Keyframe::new(1.0, 10.0)])
1004 .unwrap(),
1005 timing: Timing::new(Duration::from_millis(100)),
1006 samples,
1007 }
1008 });
1009 cx.run_until_parked();
1010 assert_eq!(samples.borrow().last().unwrap().value, 0.0);
1011 assert_eq!(
1012 samples.borrow().last().unwrap().status,
1013 MotionStatus::Running
1014 );
1015
1016 cx.executor().advance_clock(Duration::from_millis(50));
1017 assert_eq!(
1018 window
1019 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1020 .unwrap(),
1021 1
1022 );
1023 cx.run_until_parked();
1024 assert_eq!(samples.borrow().last().unwrap().value, 5.0);
1025
1026 cx.executor().advance_clock(Duration::from_millis(50));
1027 window.update(cx, |_, window, _| window.refresh()).unwrap();
1028 cx.run_until_parked();
1029 assert_eq!(
1030 samples.borrow().last().unwrap().status,
1031 MotionStatus::Finished
1032 );
1033 window
1034 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1035 .unwrap();
1036 cx.run_until_parked();
1037 assert_eq!(
1038 window
1039 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1040 .unwrap(),
1041 0
1042 );
1043 }
1044
1045 struct PresenceView {
1046 present: Rc<Cell<bool>>,
1047 samples: Rc<RefCell<Vec<PresenceSample>>>,
1048 }
1049
1050 impl Render for PresenceView {
1051 fn render(
1052 &mut self,
1053 window: &mut Window,
1054 cx: &mut wgpui::Context<Self>,
1055 ) -> impl IntoElement {
1056 self.samples.borrow_mut().push(
1057 Presence::new("presence-test", self.present.get())
1058 .transition(Transition::new(Duration::from_millis(100)).ease(|t| t))
1059 .sample(window, cx),
1060 );
1061 Empty
1062 }
1063 }
1064
1065 struct PresenceFixture {
1066 window: WindowHandle<PresenceView>,
1067 present: Rc<Cell<bool>>,
1068 samples: Rc<RefCell<Vec<PresenceSample>>>,
1069 }
1070
1071 impl PresenceFixture {
1072 fn open(cx: &mut TestAppContext, initially_present: bool) -> Self {
1073 let present = Rc::new(Cell::new(initially_present));
1074 let samples = Rc::new(RefCell::new(Vec::new()));
1075 let window = cx.open_window(size(px(100.), px(100.)), {
1076 let present = present.clone();
1077 let samples = samples.clone();
1078 move |_, _| PresenceView { present, samples }
1079 });
1080 cx.run_until_parked();
1081 Self {
1082 window,
1083 present,
1084 samples,
1085 }
1086 }
1087
1088 fn render(&self, cx: &mut TestAppContext, present: bool) -> PresenceSample {
1089 self.present.set(present);
1090 self.window
1091 .update(cx, |_, window, _| window.refresh())
1092 .unwrap();
1093 cx.run_until_parked();
1094 *self.samples.borrow().last().unwrap()
1095 }
1096 }
1097
1098 #[wgpui::test]
1099 fn presence_enters_exits_and_only_unmounts_after_exit(cx: &mut TestAppContext) {
1100 let fixture = PresenceFixture::open(cx, true);
1101 let entering = *fixture.samples.borrow().last().unwrap();
1102 assert_eq!(entering.phase, PresencePhase::Entering);
1103 assert_eq!(entering.progress, 0.0);
1104 assert!(entering.should_render());
1105
1106 cx.executor().advance_clock(Duration::from_millis(100));
1107 let present = fixture.render(cx, true);
1108 assert_eq!(present.phase, PresencePhase::Present);
1109 assert_eq!(present.progress, 1.0);
1110
1111 let exiting = fixture.render(cx, false);
1112 assert_eq!(exiting.phase, PresencePhase::Exiting);
1113 assert_eq!(exiting.progress, 1.0);
1114 assert!(exiting.should_render());
1115
1116 cx.executor().advance_clock(Duration::from_millis(100));
1117 let absent = fixture.render(cx, false);
1118 assert_eq!(absent.phase, PresencePhase::Absent);
1119 assert_eq!(absent.progress, 0.0);
1120 assert!(!absent.should_render());
1121 }
1122
1123 #[wgpui::test]
1124 fn presence_reentry_reverses_from_the_exit_sample(cx: &mut TestAppContext) {
1125 let fixture = PresenceFixture::open(cx, true);
1126 cx.executor().advance_clock(Duration::from_millis(100));
1127 fixture.render(cx, true);
1128 fixture.render(cx, false);
1129 cx.executor().advance_clock(Duration::from_millis(40));
1130 let reentering = fixture.render(cx, true);
1131
1132 assert_eq!(reentering.phase, PresencePhase::Entering);
1133 assert_eq!(reentering.progress, 0.6);
1134 }
1135
1136 #[wgpui::test]
1137 fn reduced_motion_resolves_presence_without_a_pending_frame(cx: &mut TestAppContext) {
1138 cx.update(|cx| cx.set_reduce_motion(true));
1139 let fixture = PresenceFixture::open(cx, true);
1140 assert_eq!(
1141 fixture.samples.borrow().last().unwrap().phase,
1142 PresencePhase::Present
1143 );
1144 assert_eq!(
1145 fixture
1146 .window
1147 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1148 .unwrap(),
1149 0
1150 );
1151 assert_eq!(fixture.render(cx, false).phase, PresencePhase::Absent);
1152 }
1153
1154 struct SequenceView {
1155 steps: Rc<RefCell<Vec<SequenceStep<f32>>>>,
1156 samples: Rc<RefCell<Vec<SequenceSample<f32>>>>,
1157 }
1158
1159 impl Render for SequenceView {
1160 fn render(
1161 &mut self,
1162 window: &mut Window,
1163 cx: &mut wgpui::Context<Self>,
1164 ) -> impl IntoElement {
1165 self.samples.borrow_mut().push(
1166 Sequence::new("sequence-test", 0.0)
1167 .with_steps(self.steps.borrow().iter().cloned())
1168 .sample(window, cx),
1169 );
1170 Empty
1171 }
1172 }
1173
1174 struct SequenceFixture {
1175 window: WindowHandle<SequenceView>,
1176 steps: Rc<RefCell<Vec<SequenceStep<f32>>>>,
1177 samples: Rc<RefCell<Vec<SequenceSample<f32>>>>,
1178 }
1179
1180 impl SequenceFixture {
1181 fn open(cx: &mut TestAppContext, steps: Vec<SequenceStep<f32>>) -> Self {
1182 let steps = Rc::new(RefCell::new(steps));
1183 let samples = Rc::new(RefCell::new(Vec::new()));
1184 let window = cx.open_window(size(px(100.), px(100.)), {
1185 let steps = steps.clone();
1186 let samples = samples.clone();
1187 move |_, _| SequenceView { steps, samples }
1188 });
1189 cx.run_until_parked();
1190 Self {
1191 window,
1192 steps,
1193 samples,
1194 }
1195 }
1196
1197 fn linear(millis: u64) -> Transition {
1198 Transition::new(Duration::from_millis(millis)).ease(|t| t)
1199 }
1200
1201 fn last(&self) -> SequenceSample<f32> {
1202 *self.samples.borrow().last().unwrap()
1203 }
1204
1205 fn render(&self, cx: &mut TestAppContext) -> SequenceSample<f32> {
1206 self.window
1207 .update(cx, |_, window, _| window.refresh())
1208 .unwrap();
1209 cx.run_until_parked();
1210 self.last()
1211 }
1212
1213 fn advance(&self, cx: &mut TestAppContext, millis: u64) -> SequenceSample<f32> {
1214 cx.executor().advance_clock(Duration::from_millis(millis));
1215 self.render(cx)
1216 }
1217
1218 fn pending_frame(&self, cx: &mut TestAppContext) -> usize {
1219 self.window
1220 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1221 .unwrap()
1222 }
1223 }
1224
1225 fn assert_sample(sample: SequenceSample<f32>, value: f32, step: usize, status: MotionStatus) {
1226 assert_eq!(
1227 (*sample.value(), sample.step(), sample.status()),
1228 (value, step, status)
1229 );
1230 }
1231
1232 #[wgpui::test]
1233 fn sequence_steps_advance_in_order_at_their_boundaries(cx: &mut TestAppContext) {
1234 let fixture = SequenceFixture::open(
1235 cx,
1236 vec![
1237 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1238 SequenceStep::new(
1239 20.0,
1240 SequenceFixture::linear(100).delay(Duration::from_millis(50)),
1241 ),
1242 ],
1243 );
1244 assert_sample(fixture.last(), 0.0, 0, MotionStatus::Running);
1245 assert_sample(fixture.advance(cx, 50), 5.0, 0, MotionStatus::Running);
1246
1247 assert_sample(fixture.advance(cx, 50), 10.0, 1, MotionStatus::Delayed);
1250 assert_sample(fixture.advance(cx, 50), 10.0, 1, MotionStatus::Running);
1251 assert_sample(fixture.advance(cx, 50), 15.0, 1, MotionStatus::Running);
1252 assert_sample(fixture.advance(cx, 50), 20.0, 1, MotionStatus::Finished);
1253 }
1254
1255 #[wgpui::test]
1256 fn a_sequence_starts_its_next_step_where_the_previous_ended_not_at_the_frame(
1257 cx: &mut TestAppContext,
1258 ) {
1259 let fixture = SequenceFixture::open(
1260 cx,
1261 vec![
1262 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1263 SequenceStep::new(20.0, SequenceFixture::linear(100)),
1264 ],
1265 );
1266 fixture.advance(cx, 50);
1269 assert_sample(fixture.advance(cx, 125), 17.5, 1, MotionStatus::Running);
1270 }
1271
1272 #[wgpui::test]
1273 fn zero_duration_steps_complete_within_the_frame_that_reaches_them(cx: &mut TestAppContext) {
1274 let fixture = SequenceFixture::open(
1275 cx,
1276 vec![
1277 SequenceStep::new(5.0, SequenceFixture::linear(0)),
1278 SequenceStep::new(6.0, SequenceFixture::linear(0)),
1279 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1280 ],
1281 );
1282 assert_sample(fixture.last(), 6.0, 2, MotionStatus::Running);
1283 assert_sample(fixture.advance(cx, 50), 8.0, 2, MotionStatus::Running);
1284 }
1285
1286 #[wgpui::test]
1287 fn a_sequence_reports_finished_once_and_then_stops_requesting_frames(cx: &mut TestAppContext) {
1288 let fixture = SequenceFixture::open(
1289 cx,
1290 vec![
1291 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1292 SequenceStep::new(20.0, SequenceFixture::linear(100)),
1293 ],
1294 );
1295 assert_eq!(fixture.pending_frame(cx), 1);
1296 cx.run_until_parked();
1297
1298 cx.executor().advance_clock(Duration::from_millis(100));
1299 assert_eq!(fixture.pending_frame(cx), 1);
1300 cx.run_until_parked();
1301 assert_eq!(fixture.last().status(), MotionStatus::Running);
1302 assert!(
1303 fixture
1304 .samples
1305 .borrow()
1306 .iter()
1307 .all(|sample| !sample.is_finished()),
1308 "the first step's end must not read as the sequence finishing"
1309 );
1310
1311 assert_sample(fixture.advance(cx, 100), 20.0, 1, MotionStatus::Finished);
1312 fixture.pending_frame(cx);
1313 cx.run_until_parked();
1314 assert_eq!(fixture.pending_frame(cx), 0);
1315 assert_sample(fixture.advance(cx, 1_000), 20.0, 1, MotionStatus::Finished);
1316 }
1317
1318 #[wgpui::test]
1319 fn reduced_motion_adopts_a_sequences_last_target_without_requesting_a_frame(
1320 cx: &mut TestAppContext,
1321 ) {
1322 cx.update(|cx| cx.set_reduce_motion(true));
1323 let fixture = SequenceFixture::open(
1324 cx,
1325 vec![
1326 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1327 SequenceStep::new(20.0, SequenceFixture::linear(100)),
1328 ],
1329 );
1330 assert_sample(fixture.last(), 20.0, 1, MotionStatus::Finished);
1331 assert_eq!(fixture.pending_frame(cx), 0);
1332 }
1333
1334 #[wgpui::test]
1335 fn a_changed_step_target_restarts_the_sequence_from_the_sampled_value(cx: &mut TestAppContext) {
1336 let fixture = SequenceFixture::open(
1337 cx,
1338 vec![
1339 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1340 SequenceStep::new(20.0, SequenceFixture::linear(100)),
1341 ],
1342 );
1343 fixture.advance(cx, 150);
1344 assert_sample(fixture.last(), 15.0, 1, MotionStatus::Running);
1345
1346 *fixture.steps.borrow_mut() = vec![
1347 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1348 SequenceStep::new(35.0, SequenceFixture::linear(100)),
1349 ];
1350 assert_sample(fixture.render(cx), 15.0, 0, MotionStatus::Running);
1351 assert_sample(fixture.advance(cx, 50), 12.5, 0, MotionStatus::Running);
1352 assert_sample(fixture.advance(cx, 100), 22.5, 1, MotionStatus::Running);
1353
1354 *fixture.steps.borrow_mut() = vec![SequenceStep::new(0.0, SequenceFixture::linear(100))];
1356 assert_sample(fixture.render(cx), 22.5, 0, MotionStatus::Running);
1357 assert_sample(fixture.advance(cx, 100), 0.0, 0, MotionStatus::Finished);
1358 }
1359
1360 #[wgpui::test]
1361 fn a_change_to_a_step_not_being_played_does_not_restart_the_sequence(cx: &mut TestAppContext) {
1362 let fixture = SequenceFixture::open(
1363 cx,
1364 vec![
1365 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1366 SequenceStep::new(20.0, SequenceFixture::linear(100)),
1367 ],
1368 );
1369 fixture.advance(cx, 50);
1370 *fixture.steps.borrow_mut() = vec![
1371 SequenceStep::new(10.0, SequenceFixture::linear(100)),
1372 SequenceStep::new(30.0, SequenceFixture::linear(100)),
1373 ];
1374 assert_sample(fixture.render(cx), 5.0, 0, MotionStatus::Running);
1375 assert_sample(fixture.advance(cx, 100), 20.0, 1, MotionStatus::Running);
1376 }
1377
1378 struct SingleStepView {
1379 armed: Rc<Cell<bool>>,
1380 samples: Rc<RefCell<Vec<(SequenceSample<f32>, MotionValue<f32>)>>>,
1381 }
1382
1383 impl Render for SingleStepView {
1384 fn render(
1385 &mut self,
1386 window: &mut Window,
1387 cx: &mut wgpui::Context<Self>,
1388 ) -> impl IntoElement {
1389 let policy = Transition::new(Duration::from_millis(100))
1390 .delay(Duration::from_millis(20))
1391 .easing(Easing::EaseInOut);
1392 if !self.armed.get() {
1396 transition_with_status("plain", 0.0, policy, window, cx);
1397 return Empty;
1398 }
1399 let sequence = Sequence::new("single-step", 0.0)
1400 .with_step(10.0, policy.clone())
1401 .sample(window, cx);
1402 let plain = transition_with_status("plain", 10.0, policy, window, cx);
1403 self.samples.borrow_mut().push((sequence, plain));
1404 Empty
1405 }
1406 }
1407
1408 #[wgpui::test]
1409 fn a_single_step_sequence_matches_a_plain_transition(cx: &mut TestAppContext) {
1410 let armed = Rc::new(Cell::new(false));
1411 let samples = Rc::new(RefCell::new(Vec::new()));
1412 let window = cx.open_window(size(px(100.), px(100.)), {
1413 let armed = armed.clone();
1414 let samples = samples.clone();
1415 move |_, _| SingleStepView { armed, samples }
1416 });
1417 cx.run_until_parked();
1418 armed.set(true);
1419 for millis in [0, 10, 30, 70, 120] {
1420 cx.executor().advance_clock(Duration::from_millis(millis));
1421 window.update(cx, |_, window, _| window.refresh()).unwrap();
1422 cx.run_until_parked();
1423 let (sequence, plain) = *samples.borrow().last().unwrap();
1424 assert_eq!(*sequence.value(), plain.value, "value after {millis} ms");
1425 assert_eq!(sequence.status(), plain.status, "status after {millis} ms");
1426 assert_eq!(sequence.step(), 0);
1427 }
1428 }
1429
1430 #[wgpui::test]
1431 fn an_empty_sequence_idles_at_its_starting_value(cx: &mut TestAppContext) {
1432 let fixture = SequenceFixture::open(cx, Vec::new());
1433 assert_sample(fixture.last(), 0.0, 0, MotionStatus::Idle);
1434 assert_eq!(fixture.pending_frame(cx), 0);
1435 }
1436
1437 #[test]
1438 fn transition_ids_accept_element_like_scalars_and_named_channels() {
1439 assert_eq!(
1440 TransitionId::from("opacity"),
1441 TransitionId::from(ElementId::from("opacity"))
1442 );
1443 assert_ne!(
1444 TransitionId::from(("terms", "fill")),
1445 TransitionId::from(("terms", "mark-opacity"))
1446 );
1447 let _: TransitionId = 7usize.into();
1448 let _: TransitionId = 7i32.into();
1449 }
1450
1451 struct TestView {
1452 target: Rc<Cell<f32>>,
1453 duration: Duration,
1454 samples: Rc<RefCell<Vec<f32>>>,
1455 }
1456
1457 impl Render for TestView {
1458 fn render(
1459 &mut self,
1460 window: &mut Window,
1461 cx: &mut wgpui::Context<Self>,
1462 ) -> impl IntoElement {
1463 self.samples.borrow_mut().push(transition(
1464 ("test", "value"),
1465 self.target.get(),
1466 Transition::new(self.duration).ease(|t| t),
1467 window,
1468 cx,
1469 ));
1470 Empty
1471 }
1472 }
1473
1474 struct DelayedView {
1475 target: Rc<Cell<f32>>,
1476 samples: Rc<RefCell<Vec<f32>>>,
1477 }
1478
1479 impl Render for DelayedView {
1480 fn render(
1481 &mut self,
1482 window: &mut Window,
1483 cx: &mut wgpui::Context<Self>,
1484 ) -> impl IntoElement {
1485 self.samples.borrow_mut().push(transition(
1486 ("delayed-test", "value"),
1487 self.target.get(),
1488 Transition::new(Duration::from_millis(100))
1489 .delay(Duration::from_millis(50))
1490 .ease(|t| t),
1491 window,
1492 cx,
1493 ));
1494 Empty
1495 }
1496 }
1497
1498 struct Fixture {
1499 window: WindowHandle<TestView>,
1500 target: Rc<Cell<f32>>,
1501 samples: Rc<RefCell<Vec<f32>>>,
1502 }
1503
1504 impl Fixture {
1505 fn open(cx: &mut TestAppContext, duration: Duration) -> Self {
1506 let target = Rc::new(Cell::new(0.0));
1507 let samples = Rc::new(RefCell::new(Vec::new()));
1508 let window = cx.open_window(size(px(100.), px(100.)), {
1509 let target = target.clone();
1510 let samples = samples.clone();
1511 move |_, _| TestView {
1512 target,
1513 duration,
1514 samples,
1515 }
1516 });
1517 cx.run_until_parked();
1518 Self {
1519 window,
1520 target,
1521 samples,
1522 }
1523 }
1524
1525 fn render(&self, cx: &mut TestAppContext, target: f32) -> f32 {
1526 self.target.set(target);
1527 self.window
1528 .update(cx, |_, window, _| window.refresh())
1529 .unwrap();
1530 cx.run_until_parked();
1531 *self.samples.borrow().last().unwrap()
1532 }
1533
1534 fn pending_frame(&self, cx: &mut TestAppContext) -> usize {
1535 self.window
1536 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1537 .unwrap()
1538 }
1539 }
1540
1541 #[wgpui::test]
1542 fn a_zero_duration_target_change_is_immediate(cx: &mut TestAppContext) {
1543 let fixture = Fixture::open(cx, Duration::ZERO);
1544 assert_eq!(fixture.render(cx, 1.0), 1.0);
1545 }
1546
1547 #[wgpui::test]
1548 fn a_changed_target_transitions_over_time(cx: &mut TestAppContext) {
1549 let duration = Duration::from_millis(100);
1550 let fixture = Fixture::open(cx, duration);
1551 assert_eq!(fixture.render(cx, 10.0), 0.0);
1552
1553 cx.executor().advance_clock(Duration::from_millis(50));
1554 assert_eq!(fixture.render(cx, 10.0), 5.0);
1555 }
1556
1557 #[wgpui::test]
1558 fn requested_animation_frames_resample_without_manual_refresh(cx: &mut TestAppContext) {
1559 let duration = Duration::from_millis(100);
1560 let fixture = Fixture::open(cx, duration);
1561 assert_eq!(fixture.render(cx, 10.0), 0.0);
1562
1563 cx.executor().advance_clock(Duration::from_millis(50));
1564 assert_eq!(fixture.pending_frame(cx), 1);
1565 cx.run_until_parked();
1566
1567 assert_eq!(*fixture.samples.borrow().last().unwrap(), 5.0);
1568 }
1569
1570 #[wgpui::test]
1571 fn reversing_uses_the_current_sample_and_shortens_the_return(cx: &mut TestAppContext) {
1572 let duration = Duration::from_millis(100);
1573 let fixture = Fixture::open(cx, duration);
1574 assert_eq!(fixture.render(cx, 10.0), 0.0);
1575
1576 cx.executor().advance_clock(Duration::from_millis(50));
1577 assert_eq!(fixture.render(cx, 0.0), 5.0);
1578 cx.executor().advance_clock(Duration::from_millis(25));
1579 assert_eq!(fixture.render(cx, 0.0), 2.5);
1580 }
1581
1582 #[wgpui::test]
1583 fn delay_holds_the_previous_value_before_interpolation(cx: &mut TestAppContext) {
1584 let target = Rc::new(Cell::new(0.0));
1585 let samples = Rc::new(RefCell::new(Vec::new()));
1586 let window = cx.open_window(size(px(100.), px(100.)), {
1587 let target = target.clone();
1588 let samples = samples.clone();
1589 move |_, _| DelayedView { target, samples }
1590 });
1591 cx.run_until_parked();
1592
1593 target.set(10.0);
1594 window.update(cx, |_, window, _| window.refresh()).unwrap();
1595 cx.run_until_parked();
1596 assert_eq!(*samples.borrow().last().unwrap(), 0.0);
1597
1598 cx.executor().advance_clock(Duration::from_millis(50));
1599 window.update(cx, |_, window, _| window.refresh()).unwrap();
1600 cx.run_until_parked();
1601 assert_eq!(*samples.borrow().last().unwrap(), 0.0);
1602
1603 cx.executor().advance_clock(Duration::from_millis(50));
1604 window.update(cx, |_, window, _| window.refresh()).unwrap();
1605 cx.run_until_parked();
1606 assert_eq!(*samples.borrow().last().unwrap(), 5.0);
1607 }
1608
1609 #[wgpui::test]
1610 fn a_completed_transition_stops_requesting_frames(cx: &mut TestAppContext) {
1611 let duration = Duration::from_millis(100);
1612 let fixture = Fixture::open(cx, duration);
1613 fixture.render(cx, 1.0);
1614 assert_eq!(fixture.pending_frame(cx), 1);
1615
1616 cx.executor().advance_clock(duration);
1617 assert_eq!(fixture.render(cx, 1.0), 1.0);
1618 fixture.pending_frame(cx);
1619 cx.run_until_parked();
1620 assert_eq!(fixture.pending_frame(cx), 0);
1621 }
1622
1623 #[wgpui::test]
1624 fn reduced_motion_adopts_the_target_without_requesting_a_frame(cx: &mut TestAppContext) {
1625 cx.update(|cx| cx.set_reduce_motion(true));
1626 let duration = Duration::from_millis(100);
1627 let fixture = Fixture::open(cx, duration);
1628 assert_eq!(fixture.render(cx, 1.0), 1.0);
1629 assert_eq!(fixture.pending_frame(cx), 0);
1630 }
1631
1632 struct SpringView {
1633 target: Rc<Cell<f32>>,
1634 policy: Rc<Cell<Spring>>,
1635 samples: Rc<RefCell<Vec<f32>>>,
1636 }
1637
1638 impl Render for SpringView {
1639 fn render(
1640 &mut self,
1641 window: &mut Window,
1642 cx: &mut wgpui::Context<Self>,
1643 ) -> impl IntoElement {
1644 self.samples.borrow_mut().push(spring(
1645 ("spring-test", "value"),
1646 self.target.get(),
1647 self.policy.get(),
1648 window,
1649 cx,
1650 ));
1651 Empty
1652 }
1653 }
1654
1655 struct SpringFixture {
1656 window: WindowHandle<SpringView>,
1657 target: Rc<Cell<f32>>,
1658 policy: Rc<Cell<Spring>>,
1659 samples: Rc<RefCell<Vec<f32>>>,
1660 }
1661
1662 impl SpringFixture {
1663 fn open(cx: &mut TestAppContext, policy: Spring) -> Self {
1664 let target = Rc::new(Cell::new(0.0));
1665 let policy = Rc::new(Cell::new(policy));
1666 let samples = Rc::new(RefCell::new(Vec::new()));
1667 let window = cx.open_window(size(px(100.), px(100.)), {
1668 let target = target.clone();
1669 let policy = policy.clone();
1670 let samples = samples.clone();
1671 move |_, _| SpringView {
1672 target,
1673 policy,
1674 samples,
1675 }
1676 });
1677 cx.run_until_parked();
1678 Self {
1679 window,
1680 target,
1681 policy,
1682 samples,
1683 }
1684 }
1685
1686 fn render(&self, cx: &mut TestAppContext, target: f32) -> f32 {
1687 self.target.set(target);
1688 self.window
1689 .update(cx, |_, window, _| window.refresh())
1690 .unwrap();
1691 cx.run_until_parked();
1692 *self.samples.borrow().last().unwrap()
1693 }
1694
1695 fn advance(&self, cx: &mut TestAppContext, millis: u64, target: f32) -> f32 {
1696 cx.executor().advance_clock(Duration::from_millis(millis));
1697 self.render(cx, target)
1698 }
1699
1700 fn pending_frame(&self, cx: &mut TestAppContext) -> usize {
1701 self.window
1702 .update(cx, |_, window, cx| window.simulate_next_frame(cx))
1703 .unwrap()
1704 }
1705 }
1706
1707 #[wgpui::test]
1708 fn a_spring_adopts_its_first_target_immediately(cx: &mut TestAppContext) {
1709 let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
1710 assert_eq!(*fixture.samples.borrow().first().unwrap(), 0.0);
1711 }
1712
1713 #[wgpui::test]
1714 fn a_spring_travels_toward_its_target_over_time(cx: &mut TestAppContext) {
1715 let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
1716 assert_eq!(fixture.render(cx, 1.0), 0.0);
1717
1718 let early = fixture.advance(cx, 50, 1.0);
1719 let late = fixture.advance(cx, 50, 1.0);
1720 assert!(
1721 0.0 < early && early < late && late < 1.0,
1722 "expected monotonic approach, got {early} then {late}"
1723 );
1724 }
1725
1726 #[wgpui::test]
1727 fn a_reversed_spring_keeps_its_momentum_before_turning_around(cx: &mut TestAppContext) {
1728 let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
1729 fixture.render(cx, 1.0);
1730 let reversed_at = fixture.advance(cx, 100, 1.0);
1731
1732 assert_eq!(fixture.render(cx, 0.0), reversed_at);
1735
1736 let next = fixture.advance(cx, 16, 0.0);
1737 assert!(
1738 next > reversed_at,
1739 "expected the spring to carry its velocity past {reversed_at}, got {next}"
1740 );
1741
1742 assert_eq!(fixture.advance(cx, 1_000, 0.0), 0.0);
1743 }
1744
1745 #[wgpui::test]
1746 fn a_bouncy_spring_overshoots_its_target(cx: &mut TestAppContext) {
1747 let fixture = SpringFixture::open(
1748 cx,
1749 Spring::new(Duration::from_millis(350)).with_damping(0.7),
1750 );
1751 fixture.render(cx, 1.0);
1752 for _ in 0..30 {
1753 fixture.advance(cx, 16, 1.0);
1754 }
1755
1756 let peak = fixture
1757 .samples
1758 .borrow()
1759 .iter()
1760 .copied()
1761 .fold(f32::MIN, f32::max);
1762 assert!(peak > 1.0, "expected an overshoot past 1.0, got {peak}");
1763 }
1764
1765 #[wgpui::test]
1766 fn a_settled_spring_stops_requesting_frames(cx: &mut TestAppContext) {
1767 let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
1768 fixture.render(cx, 1.0);
1769 assert_eq!(fixture.pending_frame(cx), 1);
1770
1771 assert_eq!(fixture.advance(cx, 2_000, 1.0), 1.0);
1772 fixture.pending_frame(cx);
1773 cx.run_until_parked();
1774 assert_eq!(fixture.pending_frame(cx), 0);
1775 }
1776
1777 #[wgpui::test]
1778 fn a_spring_that_is_not_travelling_adopts_its_target_on_the_spot(cx: &mut TestAppContext) {
1779 let travelling = Spring::new(Duration::from_millis(300));
1780 let fixture = SpringFixture::open(cx, travelling.with_travel(false));
1781
1782 assert_eq!(fixture.render(cx, 1.0), 1.0);
1783 assert_eq!(fixture.pending_frame(cx), 0);
1784 assert_eq!(fixture.advance(cx, 100, 5.0), 5.0);
1785
1786 fixture.policy.set(travelling);
1789 assert_eq!(fixture.render(cx, 6.0), 5.0);
1790 let next = fixture.advance(cx, 50, 6.0);
1791 assert!(
1792 5.0 < next && next < 6.0,
1793 "expected travel to resume from 5.0, got {next}"
1794 );
1795 }
1796
1797 #[wgpui::test]
1798 fn a_zero_response_spring_resolves_instead_of_dividing_by_its_period(cx: &mut TestAppContext) {
1799 let fixture = SpringFixture::open(cx, Spring::new(Duration::ZERO));
1800 assert_eq!(fixture.render(cx, 1.0), 1.0);
1801 assert_eq!(fixture.pending_frame(cx), 0);
1802 }
1803
1804 #[test]
1805 fn spring_rejects_non_finite_or_negative_physical_parameters() {
1806 let spring = Spring::new(Duration::from_millis(300));
1807
1808 assert_eq!(
1809 spring.try_with_damping(f32::NAN).unwrap_err(),
1810 SpringError::InvalidDamping
1811 );
1812 assert_eq!(
1813 spring.try_with_damping(-0.1).unwrap_err(),
1814 SpringError::InvalidDamping
1815 );
1816 assert_eq!(
1817 spring.try_with_epsilon(f32::INFINITY).unwrap_err(),
1818 SpringError::InvalidEpsilon
1819 );
1820 assert_eq!(
1821 spring.try_with_epsilon(-0.1).unwrap_err(),
1822 SpringError::InvalidEpsilon
1823 );
1824 }
1825
1826 #[test]
1827 fn spring_reports_its_unit_specific_settling_tolerance() {
1828 let normalized = Spring::new(Duration::from_millis(180));
1829 let pixels = Spring::new(Duration::from_millis(180)).with_epsilon(0.1);
1830
1831 assert!(normalized.epsilon() < 0.01);
1832 assert_eq!(pixels.epsilon(), 0.1);
1833 }
1834
1835 #[wgpui::test]
1836 fn reduced_motion_adopts_the_spring_target_without_requesting_a_frame(cx: &mut TestAppContext) {
1837 cx.update(|cx| cx.set_reduce_motion(true));
1838 let fixture = SpringFixture::open(
1839 cx,
1840 Spring::new(Duration::from_millis(350)).with_damping(0.7),
1841 );
1842 assert_eq!(fixture.render(cx, 1.0), 1.0);
1843 assert_eq!(fixture.pending_frame(cx), 0);
1844 }
1845}