glissade 0.2.10

Rust library that provides various utilities for animations and transitions
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
use super::animation_struct::Animation;
use super::keyframes_easing::EasingKeyframes;
use super::keyframes_linear::LinearKeyframes;
use super::keyframes_repeat::RepeatKeyframes;
use super::keyframes_repeat_n::RepeatNKeyframes;
use super::keyframes_reverse::ReverseKeyframes;
use super::keyframes_scale::ScaleKeyframes;
use super::keyframes_sequential::SequentialKeyframes;
use super::keyframes_stay::StayKeyframes;
use crate::animation::keyframes_apply_easing::ApplyEasingKeyframes;
use crate::animation::keyframes_function::FunctionKeyframes;
use crate::animation::keyframes_map::MapKeyframes;
use crate::animation::keyframes_poly::PolyKeyframes;
use crate::animation::keyframes_slice::SliceKeyframes;
use crate::{Distance, Easing, Mix, Time};
use std::iter::once;

/// A transition of a value over time. It works like an animation template, or set of keyframes.
pub trait Keyframes<T, X: Time> {
    /// Get the value at a specific time offset from the start.
    /// If the offset is greater than the duration, the value at the end of the animation is returned.
    fn get(&self, offset: X::Duration) -> T;

    /// Get the duration of the animation.
    /// If the animation is infinite, it will panic.
    fn duration(&self) -> X::Duration;

    /// Check if the animation is finished at the given offset.
    fn is_finished(&self, offset: X::Duration) -> bool {
        self.is_finite() && self.duration() <= offset
    }

    /// Check if the animation is finite.
    fn is_finite(&self) -> bool;

    /// Get the value of the animation at the start.
    fn start_value(&self) -> T {
        self.get(Default::default())
    }

    /// Get the value of the animation at the end.
    /// If the animation is infinite, it will panic.
    fn end_value(&self) -> T {
        self.get(self.duration())
    }

    /// Create an animation that stays at the end value for the given duration.
    fn stay(self, duration: X::Duration) -> SequentialKeyframes<T, X, Self, StayKeyframes<T, X>>
    where
        T: Clone,
        Self: Sized,
    {
        let end_value = self.end_value();
        SequentialKeyframes::new(self, StayKeyframes::new(end_value, duration))
    }

    /// Create an animation that linearly interpolates between the end value and the target value.
    fn go_to(
        self,
        target: T,
        duration: X::Duration,
    ) -> SequentialKeyframes<T, X, Self, LinearKeyframes<T, X>>
    where
        T: Mix + Clone,
        Self: Sized,
    {
        let end_value = self.end_value();
        SequentialKeyframes::new(self, LinearKeyframes::new(end_value, target, duration))
    }

    /// Create an animation that eases between the end value and the target value.
    fn ease_to(
        self,
        target: T,
        duration: X::Duration,
        easing: Easing,
    ) -> SequentialKeyframes<T, X, Self, EasingKeyframes<T, X>>
    where
        T: Mix + Clone,
        Self: Sized,
    {
        let end_value = self.end_value();
        SequentialKeyframes::new(
            self,
            EasingKeyframes::new(end_value, target, duration, easing),
        )
    }

    /// Create an animation that follows the given polynomial curve with easing.
    fn poly_to(
        self,
        points: impl IntoIterator<Item = T>,
        duration: X::Duration,
        easing: Easing,
    ) -> SequentialKeyframes<T, X, Self, PolyKeyframes<T, X>>
    where
        Self: Sized,
        T: Mix + Clone + Distance,
    {
        let points = once(self.end_value()).chain(points).collect();
        SequentialKeyframes::new(self, PolyKeyframes::new(points, duration, easing))
    }

    /// Follows the given function.
    fn function<F: Fn(X::Duration) -> T>(
        self,
        function: F,
        duration: X::Duration,
    ) -> SequentialKeyframes<T, X, Self, FunctionKeyframes<T, X, F>>
    where
        Self: Sized,
    {
        SequentialKeyframes::new(self, FunctionKeyframes::new(function, duration))
    }

    /// Create an animation that repeats the given keyframes indefinitely.
    fn repeat(self) -> RepeatKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        RepeatKeyframes::new(self)
    }

    /// Create an animation that repeats the given keyframes n times.
    /// * `n` - The number of times to repeat the keyframes. It can be not integer, and repeat the keyframes partially.
    fn repeat_n(self, n: f32) -> RepeatNKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        RepeatNKeyframes::new(self, n)
    }

    /// Inverse keyframes order.
    fn reverse(self) -> ReverseKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        ReverseKeyframes::new(self)
    }

    /// Scale the time of the animation by the given factor.
    fn scale(self, scale: f32) -> ScaleKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        ScaleKeyframes::new(self, scale)
    }

    /// Scale the time of the animation to the given duration.
    fn scale_to(self, new_duration: X::Duration) -> ScaleKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        let scale = if self.duration() == Default::default() {
            1.0
        } else {
            X::duration_as_f32(new_duration) / X::duration_as_f32(self.duration())
        };

        ScaleKeyframes::new(self, scale)
    }

    /// Apply easing to the keyframes.
    /// It can be useful to apply easing to slices of keyframes to go along a path segment with easing.
    fn apply_easing(self, easing: Easing) -> ApplyEasingKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        ApplyEasingKeyframes::new(self, easing)
    }

    /// Concatenate two keyframes set.
    fn then<S: Keyframes<T, X>>(self, other: S) -> SequentialKeyframes<T, X, Self, S>
    where
        Self: Sized,
    {
        SequentialKeyframes::new(self, other)
    }

    /// Get a slice of the keyframes from the start to the end.
    fn slice(self, start_offset: X::Duration, end_offset: X::Duration) -> SliceKeyframes<T, X, Self>
    where
        Self: Sized,
    {
        SliceKeyframes::new(self, (start_offset, end_offset))
    }

    fn map<R, F>(self, f: F) -> MapKeyframes<T, R, X, Self, F>
    where
        F: Fn(T) -> R,
        Self: Sized,
    {
        MapKeyframes::new(self, f)
    }

    /// Run keyframes at a specific time.
    /// * `start_time` - The time to start the transition, usually `Instant::now()`.
    fn run(self, start_time: X) -> Animation<T, X, Self>
    where
        Self: Sized,
    {
        Animation::start(self, start_time)
    }
}

fn max<X: PartialOrd>(v1: X, v2: X) -> X {
    if v1 > v2 {
        v1
    } else {
        v2
    }
}

impl<X, T, K> Keyframes<(T,), X> for (K,)
where
    X: Time,
    K: Keyframes<T, X>,
{
    fn get(&self, offset: X::Duration) -> (T,) {
        (self.0.get(offset),)
    }

    fn duration(&self) -> X::Duration {
        self.0.duration()
    }

    fn is_finite(&self) -> bool {
        self.0.is_finite()
    }
}

impl<X, T1, T2, K1, K2> Keyframes<(T1, T2), X> for (K1, K2)
where
    X: Time,
    K1: Keyframes<T1, X>,
    K2: Keyframes<T2, X>,
{
    fn get(&self, offset: X::Duration) -> (T1, T2) {
        (self.0.get(offset), self.1.get(offset))
    }

    fn duration(&self) -> X::Duration {
        max(self.0.duration(), self.1.duration())
    }

    fn is_finite(&self) -> bool {
        self.0.is_finite() && self.1.is_finite()
    }
}

impl<X, T1, T2, T3, K1, K2, K3> Keyframes<(T1, T2, T3), X> for (K1, K2, K3)
where
    X: Time,
    K1: Keyframes<T1, X>,
    K2: Keyframes<T2, X>,
    K3: Keyframes<T3, X>,
{
    fn get(&self, offset: X::Duration) -> (T1, T2, T3) {
        (self.0.get(offset), self.1.get(offset), self.2.get(offset))
    }

    fn duration(&self) -> X::Duration {
        let d0 = self.0.duration();
        let d1 = self.1.duration();
        let d2 = self.2.duration();
        max(d0, max(d1, d2))
    }

    fn is_finite(&self) -> bool {
        self.0.is_finite() && self.1.is_finite() && self.2.is_finite()
    }
}

impl<X, T1, T2, T3, T4, K1, K2, K3, K4> Keyframes<(T1, T2, T3, T4), X> for (K1, K2, K3, K4)
where
    X: Time,
    K1: Keyframes<T1, X>,
    K2: Keyframes<T2, X>,
    K3: Keyframes<T3, X>,
    K4: Keyframes<T4, X>,
{
    fn get(&self, offset: X::Duration) -> (T1, T2, T3, T4) {
        (
            self.0.get(offset),
            self.1.get(offset),
            self.2.get(offset),
            self.3.get(offset),
        )
    }

    fn duration(&self) -> X::Duration {
        let d0 = self.0.duration();
        let d1 = self.1.duration();
        let d2 = self.2.duration();
        let d3 = self.3.duration();
        max(max(d0, d1), max(d2, d3))
    }

    fn is_finite(&self) -> bool {
        self.0.is_finite() && self.1.is_finite() && self.2.is_finite() && self.3.is_finite()
    }
}

/// Start `Animation` constructing with this module.
/// * `keyframes::from` - to start keyframes at a specific point.
/// * `keyframes::stay` - to create a keyframes that stays at point for a while.
/// * `keyframes::line` - to create a keyframes that linearly goes from one point to another.
/// * `keyframes::ease` - to create a keyframes that goes from one point to another with easing.
/// * `keyframes::poly` - to create a keyframes that goes along a path.
/// * `keyframes::function` - to create a keyframes that goes along a functionally defined path.
///
/// See [`Keyframes`] trait methods for more ways of adding next frames and building an animation.
///
/// # Examples
///
/// ```
/// use std::time::Instant;
/// use glissade::{keyframes, Keyframes};
/// use web_time::Duration;
///
/// let transition = keyframes::stay::<f64, Instant>(5.0, Duration::from_secs(1))
///     .go_to(9.0, Duration::from_secs(4))
///     .repeat_n(2.0);
///
/// assert_eq!(transition.get(Duration::from_secs(0)), 5.0);
/// assert_eq!(transition.get(Duration::from_secs(1)), 5.0);
/// assert_eq!(transition.get(Duration::from_secs(2)), 6.0);
/// assert_eq!(transition.get(Duration::from_secs(3)), 7.0);
/// assert_eq!(transition.get(Duration::from_secs(4)), 8.0);
/// assert_eq!(transition.get(Duration::from_millis(4500)), 8.5);
/// assert_eq!(transition.get(Duration::from_secs(6)), 5.0);
/// assert_eq!(transition.get(Duration::from_secs(74)), 9.0);
/// ```
pub mod keyframes {
    use super::Keyframes;
    use crate::animation::keyframes_easing::EasingKeyframes;
    use crate::animation::keyframes_function::FunctionKeyframes;
    use crate::animation::keyframes_linear::LinearKeyframes;
    use crate::animation::keyframes_poly::PolyKeyframes;
    use crate::animation::keyframes_stay::StayKeyframes;
    use crate::{Distance, Easing, Mix, Time};

    pub fn from<T: Clone, X: Time>(point: T) -> impl Keyframes<T, X> {
        stay(point, Default::default())
    }

    /// Create a new keyframes that stays at a single value.
    pub fn stay<T: Clone, X: Time>(value: T, duration: X::Duration) -> impl Keyframes<T, X> {
        StayKeyframes::new(value, duration)
    }

    /// Create a new keyframes that linearly go from one value to another.
    pub fn line<T: Mix + Clone, X: Time>(
        start: T,
        end: T,
        duration: X::Duration,
    ) -> impl Keyframes<T, X> {
        LinearKeyframes::new(start, end, duration)
    }

    /// Create a new keyframes that go from one value to another with easing.
    pub fn ease<T: Mix + Clone, X: Time>(
        start: T,
        end: T,
        duration: X::Duration,
        easing: Easing,
    ) -> impl Keyframes<T, X> {
        EasingKeyframes::new(start, end, duration, easing)
    }

    /// Create a new keyframes that goes along a path.
    pub fn poly<T: Mix + Distance + Clone, X: Time>(
        points: Vec<T>,
        duration: X::Duration,
        easing: Easing,
    ) -> impl Keyframes<T, X> {
        PolyKeyframes::new(points, duration, easing)
    }

    /// Create a new keyframes that goes along functionally defined path.
    pub fn function<T, X, F>(f: F, duration: X::Duration) -> impl Keyframes<T, X>
    where
        X: Time,
        F: Fn(X::Duration) -> T,
    {
        FunctionKeyframes::new(f, duration)
    }
}

//----------------------------------------------------------------
// Tests

#[cfg(test)]
mod tests {
    use super::*;
    use crate::easing::Easing;
    use crate::mix::Mix;
    use std::time::{Duration, Instant};

    #[derive(Clone, Copy, Debug, PartialEq)]
    struct TestItem(f32);

    impl Mix for TestItem {
        fn mix(self, other: Self, t: f32) -> Self {
            TestItem(self.0.mix(other.0, t))
        }
    }

    const ZERO_DURATION: Duration = Duration::from_secs(0);
    const ONE_SECOND: Duration = Duration::from_secs(1);
    const HALF_SECOND: Duration = Duration::from_millis(500);
    const ONE_AND_HALF_SECONDS: Duration = Duration::from_millis(1500);
    const TWO_SECONDS: Duration = Duration::from_secs(2);

    #[test]
    fn none_keyframes() {
        let keyframes: StayKeyframes<TestItem, Instant> =
            StayKeyframes::new(TestItem(0.0), Duration::from_secs(1));
        assert_eq!(keyframes.get(ZERO_DURATION), TestItem(0.0));
        assert_eq!(keyframes.get(HALF_SECOND), TestItem(0.0));
        assert_eq!(keyframes.get(ONE_SECOND), TestItem(0.0));
    }

    #[test]
    fn linear_keyframes() {
        let keyframes =
            LinearKeyframes::<TestItem, Instant>::new(TestItem(0.0), TestItem(1.0), ONE_SECOND);
        assert_eq!(keyframes.get(ZERO_DURATION), TestItem(0.0));
        assert_eq!(keyframes.get(HALF_SECOND), TestItem(0.5));
        assert_eq!(keyframes.get(ONE_SECOND), TestItem(1.0));
    }

    #[test]
    fn sequential_keyframes() {
        let keyframes = SequentialKeyframes::new(
            LinearKeyframes::<TestItem, Instant>::new(TestItem(0.0), TestItem(1.0), ONE_SECOND),
            LinearKeyframes::new(TestItem(1.0), TestItem(0.0), ONE_SECOND),
        );
        assert_eq!(keyframes.get(ZERO_DURATION), TestItem(0.0));
        assert_eq!(keyframes.get(HALF_SECOND), TestItem(0.5));
        assert_eq!(keyframes.get(ONE_SECOND), TestItem(1.0));
        assert_eq!(keyframes.get(ONE_AND_HALF_SECONDS), TestItem(0.5));
        assert_eq!(keyframes.get(TWO_SECONDS), TestItem(0.0));
    }

    #[test]
    fn easing_keyframes() {
        let keyframes = EasingKeyframes::<TestItem, Instant>::new(
            TestItem(0.0),
            TestItem(1.0),
            ONE_SECOND,
            Easing::QuadraticIn,
        );
        assert_eq!(keyframes.get(ZERO_DURATION), TestItem(0.0));
        assert_eq!(keyframes.get(HALF_SECOND), TestItem(0.25));
        assert_eq!(keyframes.get(ONE_SECOND), TestItem(1.0));
    }

    #[test]
    fn reversed_keyframes() {
        let keyframes = keyframes::from::<TestItem, Instant>(TestItem(0.0))
            .go_to(TestItem(1.0), ONE_SECOND)
            .reverse();

        assert_eq!(keyframes.get(ZERO_DURATION), TestItem(1.0));
        assert_eq!(keyframes.get(HALF_SECOND), TestItem(0.5));
        assert_eq!(keyframes.get(ONE_SECOND), TestItem(0.0));
    }

    #[test]
    fn map_keyframes() {
        let keyframes = keyframes::from::<f32, Instant>(0.0)
            .go_to(1.0, ONE_SECOND)
            .map(TestItem);

        assert_eq!(keyframes.get(ZERO_DURATION), TestItem(0.0));
        assert_eq!(keyframes.get(HALF_SECOND), TestItem(0.5));
        assert_eq!(keyframes.get(ONE_SECOND), TestItem(1.0));
    }

    #[test]
    fn scale_keyframes() {
        let keyframes = keyframes::from::<f32, Instant>(0.0)
            .go_to(1.0, ONE_SECOND)
            .scale(2.0);

        assert_eq!(keyframes.get(ZERO_DURATION), 0.0);
        assert_eq!(keyframes.get(HALF_SECOND), 0.25);
        assert_eq!(keyframes.get(ONE_SECOND), 0.5);
        assert_eq!(keyframes.get(ONE_SECOND * 2), 1.0);
    }
}