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