Skip to main content

wgpui_base/
motion.rs

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
32/// Matches GPUI's own default spring settling tolerance.
33const DEFAULT_SPRING_EPSILON: f32 = 0.001;
34
35/// A value that can be interpolated between two application-owned targets.
36pub 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/// A presentation-neutral bundle for coordinated paint transforms.
65#[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/// CSS-like timing policy for a target-value transition.
107///
108/// This type is intentionally separate from [`crate::animation::Transition`],
109/// whose legacy interface applies concrete fade, slide, and size effects to an
110/// element. A value transition never chooses a visual property for the caller.
111#[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    /// The easing curve, for a caller that samples one timeline at several
147    /// offsets, such as a staggered plot appear.
148    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    /// The elapsed time at which [`Self::progress`] over the transition's own
166    /// duration first reports `Finished`.
167    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/// Identifies one independently transitioning value.
182#[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
260/// Returns the current value for a CSS-like transition toward `target`.
261///
262/// State is keyed by `id`. The first value is adopted immediately; later target
263/// changes transition from the value sampled at that instant. Components opt
264/// into this function explicitly—base components do not install default motion.
265///
266/// Call this while rendering an element, where GPUI keyed element state is
267/// available. A channel id must identify one value type within that element.
268pub 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        // f32 seconds can round a 100 ms transition beyond its exact end.
335        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
369/// Samples a keyed keyframe playback and requests frames while it is active.
370///
371/// The stable `id` owns the playback's start time. Re-rendering with the same
372/// ID continues that playback; it does not restart when `keyframes` or `timing`
373/// is reconstructed. To replay a sequence, include an application-owned
374/// generation in the ID, for example `("notification-enter", generation)`.
375pub 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/// A physical spring policy for [`spring`].
414///
415/// A spring is the counterpart to [`Transition`] for values that can be
416/// retargeted while they are still moving. A duration-based transition restarts
417/// its easing from the value sampled at that instant, which is continuous in
418/// position but not in velocity. A spring carries velocity across the retarget,
419/// so a value reversed mid-flight decelerates and turns around instead of
420/// snapping to a new curve's initial speed.
421#[derive(Clone, Copy, Debug)]
422pub struct Spring {
423    response: Duration,
424    damping: f32,
425    epsilon: f32,
426    travel: bool,
427}
428
429/// Invalid physical or settling parameters for a [`Spring`].
430#[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    /// Builds a spring that reaches its target in about `response` without
451    /// overshooting it.
452    ///
453    /// `response` is not a duration in the sense [`Transition::new`] means one.
454    /// A spring has no end to schedule: this is the period one full oscillation
455    /// would take without damping, which is the scale the motion is felt at
456    /// rather than the moment it stops. The remaining fraction of a percent
457    /// keeps settling past it, until it is within the tolerance
458    /// [`Self::with_epsilon`] sets.
459    ///
460    /// A zero response adopts the target on the spot, as a zero duration does
461    /// for a transition. Say that with [`Self::with_travel`] where it is what
462    /// you mean; a zero here is the degenerate case, defined so an infinitely
463    /// stiff spring resolves rather than dividing by its own period.
464    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    /// Sets the damping ratio, which is `1.0` — no overshoot — by default.
474    ///
475    /// Below `1.0` the spring passes its target and comes back; above `1.0` it
476    /// approaches slowly. Overshoot suits a value with room to pass its target
477    /// and nothing to collide with. A height, an opacity, or anything bounded by
478    /// the geometry around it should stay at the default.
479    ///
480    /// This is $\zeta$, not GPUI's `SpringConfig::damping`, which is the
481    /// coefficient $c = 2 \zeta \omega_0$.
482    ///
483    /// # Panics
484    ///
485    /// Panics when `ratio` is negative or non-finite. Use
486    /// [`Self::try_with_damping`] when the value is not a trusted constant.
487    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    /// Checked form of [`Self::with_damping`].
495    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    /// Sets whether the spring travels to its target or adopts it on the spot.
504    ///
505    /// A value the pointer is already moving — a panel being dragged by its
506    /// resize handle — must not lag behind the pointer, so the spring stops
507    /// travelling for as long as the drag lasts. Retained state stays pinned to
508    /// the target meanwhile, so travel resumes from the value the drag released
509    /// rather than from wherever the spring was when it began.
510    ///
511    /// This says at the call that the motion is suspended, and it says it
512    /// without disturbing the response, damping or tolerance the spring is
513    /// configured with — which a policy swapped out for the length of the drag
514    /// would have to restate or discard.
515    pub const fn with_travel(mut self, travel: bool) -> Self {
516        self.travel = travel;
517        self
518    }
519
520    /// Sets the settling tolerance, expressed in the target's own units.
521    ///
522    /// The default suits targets that move within a normalized `0..1` range. A
523    /// spring over pixels settles perceptibly sooner with a coarser tolerance,
524    /// which also ends the animation frames that the remaining sub-pixel motion
525    /// would otherwise request.
526    ///
527    /// # Panics
528    ///
529    /// Panics when `epsilon` is zero, negative, or non-finite. Use
530    /// [`Self::try_with_epsilon`] when the value is not a trusted constant.
531    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    /// Checked form of [`Self::with_epsilon`].
539    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    /// Returns the settling tolerance in the target's own units.
548    pub const fn epsilon(self) -> f32 {
549        self.epsilon
550    }
551
552    /// The physical parameters GPUI integrates. The response must be non-zero;
553    /// [`spring`] adopts the target before reaching here when it is not.
554    ///
555    /// Derived on use rather than stored, so the builders stay `const`: neither
556    /// `Duration::as_secs_f32` nor the square root that recovers a damping ratio
557    /// from a built config can be called from a `const fn`.
558    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
571/// Returns the current value for a spring travelling toward `target`.
572///
573/// State is keyed by `id` exactly as [`transition`] keys its own. The first
574/// value is adopted immediately; later target changes preserve both the current
575/// position and the current velocity, so an interrupted spring is redirected
576/// rather than restarted.
577///
578/// Call this while rendering an element, where GPUI keyed element state is
579/// available. A channel id must identify one value within that element.
580pub 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    // The overwhelmingly common case: a spring nothing is currently moving. It
607    // has no state to advance and no frame to ask for, so it never builds a
608    // config or steps one — a settled spring costs a read and two comparisons.
609    // Every branch below would return this same value and write nothing.
610    //
611    // Resting writes nothing, so `updated_at` goes stale for as long as the rest
612    // lasts. The next retarget then steps a zero displacement at zero velocity
613    // over that whole gap, which any elapsed time leaves where it is, so the
614    // stale clock cannot move the value — it only has to not produce a NaN, and
615    // every term the propagator scales is finite.
616    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    // Advance over the frame that just elapsed, which the previous target
635    // governed, before adopting the new one for the frame to come.
636    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        // The first step ends and the second begins within one frame; nothing
1248        // reports the first step as finished in between.
1249        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        // One frame at 50 ms, the next at 175 ms: the boundary at 100 ms fell
1267        // between them, and the second step is sampled as if it started there.
1268        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        // Fewer steps than the one being played is a different sequence too.
1355        *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            // A plain transition adopts its first target where a sequence
1393            // plays from `from` at once, so the transition is primed at 0.0
1394            // and both leave for 10.0 on the frame that arms the view.
1395            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        // Retarget mid-flight. A duration-based transition restarts its easing
1733        // here and moves away from 1.0 on the very next frame.
1734        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        // Travel resumes from the value the suspension left behind. A spring
1787        // that had kept the state it held beforehand would jump back to it here.
1788        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}