gpui-ce-motion 0.3.0

Declarative, interruptible animations, transitions, and text motion for GPUI CE
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Scalar presentation values, explicit updates, and bounded inertial release.
use crate::{Spring, Transition};
use std::time::Duration;

/// Deceleration and optional hard bounds for inertial motion.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Inertia {
    tau: f64,
    bounds: Option<(f64, f64)>,
    spring: Spring,
}

impl Inertia {
    /// Creates exponential deceleration. Panics for a zero time constant.
    pub fn new(time_constant: Duration) -> Self {
        assert!(
            !time_constant.is_zero(),
            "inertia time constant must be positive"
        );

        Self {
            tau: time_constant.as_secs_f64(),
            bounds: None,
            spring: Spring::default(),
        }
    }

    /// Sets finite ordered bounds. Crossing a bound switches analytically to a spring.
    pub fn bounds(mut self, min: f64, max: f64) -> Self {
        assert!(
            min.is_finite() && max.is_finite() && min <= max,
            "invalid inertia bounds"
        );
        self.bounds = Some((min, max));

        self
    }

    /// Chooses the spring used at a boundary.
    pub fn spring(mut self, spring: Spring) -> Self {
        self.spring = spring;

        self
    }

    /// Projects a resting position and clamps it to configured bounds.
    pub fn project(self, position: f64, velocity: f64) -> f64 {
        assert!(
            position.is_finite() && velocity.is_finite(),
            "non-finite projection"
        );
        let value = finite(position + velocity * self.tau);

        self.bounds
            .map_or(value, |(min, max)| value.clamp(min, max))
    }
}

impl Default for Inertia {
    fn default() -> Self {
        Self::new(Duration::from_millis(350))
    }
}

/// A scalar presentation and its velocity, in caller-chosen units per second.
#[derive(Clone, Copy, Debug)]
pub struct ValueFrame {
    value: f64,
    velocity: f64,
    active: bool,
    completed: bool,
}

impl ValueFrame {
    /// Current presentation value.
    pub fn value(self) -> f64 {
        self.value
    }

    /// Current velocity in units per second.
    pub fn velocity(self) -> f64 {
        self.velocity
    }

    /// Whether another sample is required to complete motion.
    pub fn is_animating(self) -> bool {
        self.active
    }

    /// A completion edge, consumed by this sample.
    pub fn just_completed(self) -> bool {
        self.completed
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
enum Mode {
    Transition,
    Inertia(Inertia),
}

/// A retained scalar motion value, with no timers, observers, or heap allocations.
/// Feed its samples into any native style, paint parameter, text, or derived value.
/// Arithmetic at numeric extremes saturates to finite limits; indeterminate overflow
/// resolves to zero. Use ordinary UI-sized units for meaningful physical trajectories.
#[derive(Clone, Debug)]
pub struct MotionValue {
    value: f64,
    velocity: f64,
    from: f64,
    initial_velocity: f64,
    target: f64,
    transition: Transition,
    delay: Duration,
    started: Duration,
    last: Duration,
    set_time: Duration,
    active: bool,
    completed: bool,
    mode: Mode,
}

impl MotionValue {
    /// Creates a resting value. Panics for non-finite input.
    pub fn new(value: f64) -> Self {
        assert!(value.is_finite(), "motion value must be finite");

        Self {
            value,
            velocity: 0.0,
            from: value,
            initial_velocity: 0.0,
            target: value,
            transition: Transition::Instant,
            delay: Duration::ZERO,
            started: Duration::ZERO,
            last: Duration::ZERO,
            set_time: Duration::ZERO,
            active: false,
            completed: false,
            mode: Mode::Transition,
        }
    }

    /// Last sampled value; this does not advance time.
    pub fn get(&self) -> f64 {
        self.value
    }

    pub(crate) fn active(&self) -> bool {
        self.active
    }

    pub(crate) fn target(&self) -> f64 {
        self.target
    }

    pub(crate) fn matches(&self, target: f64, transition: Transition) -> bool {
        self.mode == Mode::Transition
            && self.target == target
            && self.transition == transition
            && self.delay.is_zero()
    }

    #[cfg(feature = "text")]
    pub(crate) fn translate(&mut self, offset: f64) {
        debug_assert_eq!(self.mode, Mode::Transition);
        self.value = finite(self.value + offset);
        self.from = finite(self.from + offset);
        self.target = finite(self.target + offset);
    }

    /// Converts positive linear units while retaining trajectory, momentum and
    /// inertia bounds. Panics for a nonpositive or non-finite factor. Numeric
    /// overflow saturates using the same policy as ordinary motion arithmetic.
    /// Spring rest thresholds remain expressed in the new units.
    pub fn rescale(&mut self, factor: f64) {
        assert!(factor.is_finite() && factor > 0.0, "invalid unit scale");
        self.value = finite(self.value * factor);
        self.velocity = finite(self.velocity * factor);
        self.from = finite(self.from * factor);
        self.initial_velocity = finite(self.initial_velocity * factor);
        self.target = finite(self.target * factor);

        if let Mode::Inertia(ref mut inertia) = self.mode {
            inertia.bounds = inertia
                .bounds
                .map(|(min, max)| (finite(min * factor), finite(max * factor)));
        }
    }

    /// Last sampled velocity.
    pub fn velocity(&self) -> f64 {
        self.velocity
    }

    /// Directly sets a value and estimates velocity from elapsed time. Cancels animation.
    pub fn set(&mut self, value: f64, now: Duration) {
        assert!(value.is_finite(), "motion value must be finite");
        let now = now.max(self.last);
        let dt = now.saturating_sub(self.set_time).as_secs_f64();

        self.velocity = if dt > 0.0 {
            finite((value - self.value) / dt)
        } else {
            self.velocity
        };
        self.value = value;
        self.target = value;
        self.from = value;
        self.active = false;
        self.completed = false;
        self.last = now;
        self.set_time = now;
        self.mode = Mode::Transition;
    }

    /// Assigns a value, clears momentum, and cancels animation without a completion event.
    pub fn jump(&mut self, value: f64, now: Duration) {
        self.set(value, now);
        self.velocity = 0.0;
    }

    /// Retargets from the presentation at `now`. Identical declarations do not restart.
    pub fn animate(&mut self, target: f64, transition: Transition, now: Duration) {
        self.animate_delayed(target, transition, Duration::ZERO, now);
    }

    /// Retargets with a delay, preserving incoming spring velocity across the hold.
    pub fn animate_delayed(
        &mut self,
        target: f64,
        transition: Transition,
        delay: Duration,
        now: Duration,
    ) {
        assert!(target.is_finite(), "motion target must be finite");
        let now = now.max(self.last);

        if self.mode == Mode::Transition
            && self.target == target
            && self.transition == transition
            && self.delay == delay
        {
            return;
        }

        self.advance(now);
        self.from = self.value;
        self.initial_velocity = self.velocity;
        self.target = target;
        self.transition = transition;
        self.delay = delay;
        self.started = now;
        self.active = self.from != target || self.velocity != 0.0;
        self.mode = Mode::Transition;
        self.completed = false;
    }

    /// Starts exponential inertia from the last presentation and velocity.
    /// Bounds switch to a spring at the exact crossing time, independent of frame rate.
    pub fn coast(&mut self, inertia: Inertia, now: Duration) {
        let now = now.max(self.last);

        self.advance(now);
        self.from = self.value;
        self.initial_velocity = self.velocity;
        self.target = inertia.project(self.value, self.velocity);
        self.started = now;
        self.delay = Duration::ZERO;
        self.mode = Mode::Inertia(inertia);
        self.active = self.value != self.target || self.velocity != 0.0;
        self.completed = false;
    }

    /// Samples a monotonic clock. Reduced motion finishes immediately, including inertia.
    pub fn sample(&mut self, now: Duration, reduced_motion: bool) -> ValueFrame {
        if reduced_motion && self.active {
            self.finish();
        } else {
            self.advance(now.max(self.last));
        }

        self.last = self.last.max(now);
        let completed = std::mem::take(&mut self.completed);

        ValueFrame {
            value: self.value,
            velocity: self.velocity,
            active: self.active,
            completed,
        }
    }

    fn finish(&mut self) {
        self.value = self.target;
        self.velocity = 0.0;
        self.completed |= self.active;
        self.active = false;
    }

    fn advance(&mut self, now: Duration) {
        self.last = now;

        if !self.active {
            return;
        }

        let elapsed = now.saturating_sub(self.started);

        if elapsed < self.delay {
            self.velocity = 0.0;

            return;
        }

        let t = elapsed.saturating_sub(self.delay).as_secs_f64();

        let (value, velocity, done) = match self.mode {
            Mode::Transition => sample_transition(
                self.from,
                self.initial_velocity,
                self.target,
                self.transition,
                t,
            ),
            Mode::Inertia(config) => {
                let amplitude = finite(self.initial_velocity * config.tau);
                let end = finite(self.from + amplitude);

                let boundary = config.bounds.and_then(|(min, max)| {
                    if self.from < min {
                        Some((min, 0.0))
                    } else if self.from > max {
                        Some((max, 0.0))
                    } else if end < min || end > max {
                        let bound = if end < min { min } else { max };
                        let crossing = -config.tau * (1.0 - (bound - self.from) / amplitude).ln();

                        Some((bound, crossing.max(0.0)))
                    } else {
                        None
                    }
                });

                if let Some((bound, crossing)) = boundary
                    && t >= crossing
                {
                    let from = if crossing == 0.0 { self.from } else { bound };
                    let velocity = self.initial_velocity * (-crossing / config.tau).exp();

                    sample_transition(
                        from,
                        velocity,
                        bound,
                        Transition::Spring(config.spring),
                        t - crossing,
                    )
                } else {
                    let decay = (-t / config.tau).exp();
                    let value = finite(self.from + amplitude * (1.0 - decay));
                    let velocity = finite(self.initial_velocity * decay);

                    (
                        value,
                        velocity,
                        (end - value).abs() <= 0.001 && velocity.abs() <= 0.001,
                    )
                }
            }
        };

        self.value = value;
        self.velocity = velocity;
        self.set_time = now;

        if done {
            self.finish();
        }
    }
}

pub(crate) fn sample_transition(
    from: f64,
    velocity: f64,
    target: f64,
    transition: Transition,
    t: f64,
) -> (f64, f64, bool) {
    match transition {
        Transition::Instant => (target, 0.0, true),
        Transition::Tween(duration, easing) => {
            let seconds = duration.as_secs_f64();

            if t >= seconds {
                return (target, 0.0, true);
            }

            let (progress, derivative) = easing.sample(t / seconds);

            (
                if t == 0.0 {
                    from
                } else {
                    finite(from * (1.0 - progress) + target * progress)
                },
                finite(finite(target - from) * derivative / seconds),
                false,
            )
        }
        Transition::Spring(spring) => {
            if t == 0.0 {
                return (from, velocity, false);
            }

            let m = spring.matrix(t);
            let displacement = finite(from - target);
            let value = finite(target + m[0] * displacement + m[1] * velocity);
            let velocity = finite(m[2] * displacement + m[3] * velocity);

            (
                value,
                velocity,
                spring.is_settled(value, velocity, target, 0.001),
            )
        }
    }
}

pub(crate) fn finite(value: f64) -> f64 {
    if value.is_nan() {
        0.0
    } else {
        value.clamp(-f64::MAX, f64::MAX)
    }
}