kael 0.2.0

GPU-accelerated native UI framework for Rust — build desktop apps with Metal, DirectX, and Vulkan rendering
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
use std::{rc::Rc, time::Duration};

use crate::Styled;

/// An animation that can be applied to an element.
#[derive(Clone)]
pub struct Animation {
    duration: Duration,
    easing: Easing,
    delay: Duration,
    repeat: Repeat,
}

impl Animation {
    /// Creates a new animation with the given duration.
    pub fn new(duration: Duration) -> Self {
        Self {
            duration,
            easing: Easing::Linear,
            delay: Duration::ZERO,
            repeat: Repeat::Once,
        }
    }

    /// Sets the easing used by this animation.
    pub fn easing(mut self, easing: Easing) -> Self {
        self.easing = easing;
        self
    }

    /// Sets a custom easing function for this animation.
    pub fn with_easing(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
        self.easing = Easing::Custom(Rc::new(easing));
        self
    }

    /// Delays this animation relative to the start of its sequence.
    pub fn delay(mut self, delay: Duration) -> Self {
        self.delay = delay;
        self
    }

    /// Sets the repeat behavior for this animation.
    pub fn repeat(mut self, repeat: Repeat) -> Self {
        self.repeat = repeat;
        self
    }

    /// Repeats this animation forever.
    pub fn repeat_forever(self) -> Self {
        self.repeat(Repeat::Forever)
    }

    pub(crate) fn sample(&self, elapsed: Duration) -> AnimationSample {
        if elapsed < self.delay {
            return AnimationSample {
                delta: 0.0,
                started: false,
                finished: false,
            };
        }

        if self.duration.is_zero() {
            return AnimationSample {
                delta: 1.0,
                started: true,
                finished: self.repeat != Repeat::Forever,
            };
        }

        let local_elapsed = elapsed - self.delay;
        let local_seconds = local_elapsed.as_secs_f32();
        let duration_seconds = self.duration.as_secs_f32();

        match self.repeat {
            Repeat::Once => {
                let raw_delta = (local_seconds / duration_seconds).clamp(0.0, 1.0);
                AnimationSample {
                    delta: self.easing.sample(raw_delta),
                    started: true,
                    finished: raw_delta >= 1.0,
                }
            }
            Repeat::Count(count) => {
                let cycle_count = count.max(1);
                let total_seconds = duration_seconds * cycle_count as f32;
                if local_seconds >= total_seconds {
                    AnimationSample {
                        delta: 1.0,
                        started: true,
                        finished: true,
                    }
                } else {
                    AnimationSample {
                        delta: self
                            .easing
                            .sample((local_seconds / duration_seconds).fract()),
                        started: true,
                        finished: false,
                    }
                }
            }
            Repeat::Forever => AnimationSample {
                delta: self
                    .easing
                    .sample((local_seconds / duration_seconds).fract()),
                started: true,
                finished: false,
            },
        }
    }

    pub(crate) fn scheduled_end(&self) -> Duration {
        let active_duration = match self.repeat {
            Repeat::Once => self.duration,
            Repeat::Count(count) => self.duration.saturating_mul(count.max(1)),
            Repeat::Forever => self.duration,
        };

        self.delay + active_duration
    }
}

/// Supported easing curves for explicit animations.
#[derive(Clone)]
pub enum Easing {
    /// A linear curve.
    Linear,
    /// A quadratic ease-in curve.
    EaseIn,
    /// A quadratic ease-out curve.
    EaseOut,
    /// A quadratic ease-in-out curve.
    EaseInOut,
    /// A cubic Bezier curve with CSS-style control points.
    CubicBezier(f32, f32, f32, f32),
    /// A damped spring curve.
    Spring {
        /// Spring stiffness.
        stiffness: f32,
        /// Damping factor.
        damping: f32,
        /// Effective mass.
        mass: f32,
    },
    /// A custom easing callback.
    Custom(Rc<dyn Fn(f32) -> f32>),
}

impl Easing {
    pub(crate) fn sample(&self, delta: f32) -> f32 {
        let delta = delta.clamp(0.0, 1.0);

        match self {
            Self::Linear => easing::linear(delta),
            Self::EaseIn => easing::quadratic(delta),
            Self::EaseOut => easing::ease_out(delta),
            Self::EaseInOut => easing::ease_in_out(delta),
            Self::CubicBezier(x1, y1, x2, y2) => cubic_bezier(*x1, *y1, *x2, *y2, delta),
            Self::Spring {
                stiffness,
                damping,
                mass,
            } => spring(*stiffness, *damping, *mass, delta),
            Self::Custom(callback) => callback(delta).clamp(0.0, 1.0),
        }
    }

    /// Sample this easing at `delta` in `0..=1` (public for media keyframes).
    pub fn ease(&self, delta: f32) -> f32 {
        self.sample(delta)
    }
}

/// How to interpolate from one media keyframe toward the next.
#[derive(Clone)]
pub enum KeyframeInterpolation {
    /// Hold the value until the next keyframe (step).
    Hold,
    /// Interpolate with the given easing curve (includes `CubicBezier` handles).
    Eased(Easing),
}

/// A single media keyframe: a value at a time, with the curve used to reach the
/// following keyframe.
#[derive(Clone)]
pub struct MediaKeyframe {
    /// Keyframe time, in seconds.
    pub time: f64,
    /// Keyframe value.
    pub value: f32,
    /// Interpolation toward the following keyframe.
    pub interpolation: KeyframeInterpolation,
}

/// A keyframed scalar track sampled by the render/playback clock.
///
/// Generalizes the UI [`Keyframes`] machinery to media use — transform, opacity,
/// effect parameters, audio automation — reusing [`Easing`] (including
/// `CubicBezier` handles) for interpolation.
#[derive(Clone, Default)]
pub struct KeyframeTrack {
    keys: Vec<MediaKeyframe>,
}

impl KeyframeTrack {
    /// An empty track.
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert a keyframe (kept sorted by time) and return the track.
    pub fn with_key(mut self, time: f64, value: f32, interpolation: KeyframeInterpolation) -> Self {
        self.insert(MediaKeyframe {
            time,
            value,
            interpolation,
        });
        self
    }

    /// Insert a keyframe, keeping the track sorted by time.
    pub fn insert(&mut self, key: MediaKeyframe) {
        let index = self
            .keys
            .partition_point(|existing| existing.time <= key.time);
        self.keys.insert(index, key);
    }

    /// Number of keyframes.
    pub fn len(&self) -> usize {
        self.keys.len()
    }

    /// Whether the track has no keyframes.
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }

    /// Sample the track at `time` (seconds). Returns `default` for an empty
    /// track; clamps to the first/last value outside the keyframe range.
    pub fn sample(&self, time: f64, default: f32) -> f32 {
        let Some(first) = self.keys.first() else {
            return default;
        };
        if time <= first.time {
            return first.value;
        }
        let last = &self.keys[self.keys.len() - 1];
        if time >= last.time {
            return last.value;
        }
        let upper = self.keys.partition_point(|key| key.time <= time);
        let (k0, k1) = (&self.keys[upper - 1], &self.keys[upper]);
        match &k0.interpolation {
            KeyframeInterpolation::Hold => k0.value,
            KeyframeInterpolation::Eased(easing) => {
                let span = (k1.time - k0.time) as f32;
                let t = if span <= f32::EPSILON {
                    0.0
                } else {
                    ((time - k0.time) as f32 / span).clamp(0.0, 1.0)
                };
                k0.value + (k1.value - k0.value) * easing.ease(t)
            }
        }
    }
}

/// Repeat behavior for explicit animations.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Repeat {
    /// Play the animation once.
    Once,
    /// Play the animation a fixed number of times.
    Count(u32),
    /// Repeat the animation indefinitely.
    Forever,
}

/// A sequence of animations that can overlap with the previous step.
#[derive(Clone, Default)]
pub struct AnimationSequence {
    animations: Vec<Animation>,
}

impl AnimationSequence {
    /// Creates an empty animation sequence.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends an animation after the current sequence tail.
    pub fn then(mut self, animation: Animation) -> Self {
        let start = self
            .animations
            .iter()
            .map(Animation::scheduled_end)
            .max()
            .unwrap_or(Duration::ZERO);
        let delay = animation.delay;
        self.animations.push(animation.delay(start + delay));
        self
    }

    /// Appends a new animation with the given duration.
    pub fn then_for(self, duration: Duration) -> Self {
        self.then(Animation::new(duration))
    }

    /// Starts the most recently-added animation earlier so it overlaps the previous one.
    pub fn with_overlap(mut self, overlap: Duration) -> Self {
        if let Some(last) = self.animations.last_mut() {
            last.delay = last.delay.saturating_sub(overlap);
        }
        self
    }

    /// Consumes the sequence into its scheduled animations.
    pub fn into_animations(self) -> Vec<Animation> {
        self.animations
    }

    /// Returns the scheduled animations in this sequence.
    pub fn animations(&self) -> &[Animation] {
        &self.animations
    }
}

/// A set of keyframes that target common styled element properties.
#[derive(Clone, Default)]
pub struct Keyframes {
    frames: Vec<Keyframe>,
}

impl Keyframes {
    /// Creates an empty keyframe set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a keyframe at the given normalized time.
    pub fn at(
        mut self,
        progress: f32,
        build: impl FnOnce(StyledKeyframe) -> StyledKeyframe,
    ) -> Self {
        self.frames.push(Keyframe {
            progress: progress.clamp(0.0, 1.0),
            style: build(StyledKeyframe::default()),
        });
        self.frames
            .sort_by(|left, right| left.progress.total_cmp(&right.progress));
        self
    }

    pub(crate) fn sample(&self, progress: f32) -> StyledKeyframe {
        let progress = progress.clamp(0.0, 1.0);
        let Some(first) = self.frames.first() else {
            return StyledKeyframe::default();
        };

        if progress <= first.progress {
            return first.style;
        }

        for window in self.frames.windows(2) {
            let start = &window[0];
            let end = &window[1];
            if progress <= end.progress {
                let segment_delta = if (end.progress - start.progress).abs() <= f32::EPSILON {
                    1.0
                } else {
                    (progress - start.progress) / (end.progress - start.progress)
                };
                return start.style.interpolate(end.style, segment_delta);
            }
        }

        self.frames
            .last()
            .map(|frame| frame.style)
            .unwrap_or_default()
    }

    pub(crate) fn apply<E: Styled>(&self, element: E, progress: f32) -> E {
        self.sample(progress).apply(element)
    }
}

/// Creates a keyframe builder for explicit styled animations.
pub fn keyframes() -> Keyframes {
    Keyframes::new()
}

#[derive(Clone, Copy)]
struct Keyframe {
    progress: f32,
    style: StyledKeyframe,
}

/// A single styled keyframe.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct StyledKeyframe {
    opacity: Option<f32>,
    scale_x: Option<f32>,
    scale_y: Option<f32>,
    rotate_degrees: Option<f32>,
}

impl StyledKeyframe {
    /// Sets the target opacity.
    pub fn opacity(mut self, opacity: f32) -> Self {
        self.opacity = Some(opacity);
        self
    }

    /// Sets a uniform target scale.
    pub fn scale(mut self, factor: f32) -> Self {
        self.scale_x = Some(factor);
        self.scale_y = Some(factor);
        self
    }

    /// Sets a non-uniform target scale.
    pub fn scale_xy(mut self, x: f32, y: f32) -> Self {
        self.scale_x = Some(x);
        self.scale_y = Some(y);
        self
    }

    /// Sets the target rotation in degrees.
    pub fn rotate(mut self, degrees: f32) -> Self {
        self.rotate_degrees = Some(degrees);
        self
    }

    /// Applies this keyframe to a styled element.
    pub fn apply<E: Styled>(self, mut element: E) -> E {
        if let Some(opacity) = self.opacity {
            element = element.opacity(opacity);
        }
        if let (Some(scale_x), Some(scale_y)) = (self.scale_x, self.scale_y) {
            element = element.scale_xy(scale_x, scale_y);
        }
        if let Some(rotate_degrees) = self.rotate_degrees {
            element = element.rotate(rotate_degrees);
        }
        element
    }

    fn interpolate(self, other: Self, delta: f32) -> Self {
        Self {
            opacity: interpolate_optional(self.opacity, other.opacity, delta),
            scale_x: interpolate_optional(self.scale_x, other.scale_x, delta),
            scale_y: interpolate_optional(self.scale_y, other.scale_y, delta),
            rotate_degrees: interpolate_optional(self.rotate_degrees, other.rotate_degrees, delta),
        }
    }
}

pub(crate) struct AnimationSample {
    pub delta: f32,
    pub started: bool,
    pub finished: bool,
}

fn interpolate_optional(start: Option<f32>, end: Option<f32>, delta: f32) -> Option<f32> {
    match (start, end) {
        (Some(start), Some(end)) => Some(start + (end - start) * delta),
        (Some(value), None) | (None, Some(value)) => Some(value),
        (None, None) => None,
    }
}

fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, delta: f32) -> f32 {
    let mut low = 0.0;
    let mut high = 1.0;
    let mut t = delta;

    for _ in 0..12 {
        let x = cubic_bezier_axis(x1, x2, t);
        if x < delta {
            low = t;
        } else {
            high = t;
        }
        t = (low + high) / 2.0;
    }

    cubic_bezier_axis(y1, y2, t).clamp(0.0, 1.0)
}

fn cubic_bezier_axis(p1: f32, p2: f32, t: f32) -> f32 {
    let inverse_t = 1.0 - t;
    3.0 * inverse_t * inverse_t * t * p1 + 3.0 * inverse_t * t * t * p2 + t * t * t
}

fn spring(stiffness: f32, damping: f32, mass: f32, delta: f32) -> f32 {
    let stiffness = stiffness.max(f32::EPSILON);
    let damping = damping.max(0.0);
    let mass = mass.max(f32::EPSILON);
    let angular_frequency = (stiffness / mass).sqrt();
    let decay = (-damping * delta).exp();
    (1.0 - decay * (angular_frequency * delta).cos()).clamp(0.0, 1.0)
}

/// Common easing helpers.
pub mod easing {
    use std::f32::consts::PI;

    /// Returns the input unchanged.
    pub fn linear(delta: f32) -> f32 {
        delta
    }

    /// Applies a quadratic ease-in curve.
    pub fn quadratic(delta: f32) -> f32 {
        delta * delta
    }

    /// Applies a quadratic ease-out curve.
    pub fn ease_out(delta: f32) -> f32 {
        1.0 - (1.0 - delta).powi(2)
    }

    /// Applies a quadratic ease-in-out curve.
    pub fn ease_in_out(delta: f32) -> f32 {
        if delta < 0.5 {
            2.0 * delta * delta
        } else {
            let x = -2.0 * delta + 2.0;
            1.0 - x * x / 2.0
        }
    }

    /// Applies a quintic ease-out curve.
    pub fn ease_out_quint() -> impl Fn(f32) -> f32 {
        move |delta| 1.0 - (1.0 - delta).powi(5)
    }

    /// Plays the provided easing forward and then backward.
    pub fn bounce(easing: impl Fn(f32) -> f32) -> impl Fn(f32) -> f32 {
        move |delta| {
            if delta < 0.5 {
                easing(delta * 2.0)
            } else {
                easing((1.0 - delta) * 2.0)
            }
        }
    }

    /// Produces a soft pulsing alpha curve between two values.
    pub fn pulsating_between(min: f32, max: f32) -> impl Fn(f32) -> f32 {
        let range = max - min;

        move |delta| {
            let t = (delta * 2.0 * PI).sin();
            let breath = (t * t * t + t) / 2.0;
            let normalized_alpha = (breath + 1.0) / 2.0;
            min + normalized_alpha * range
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Animation, AnimationSequence, Repeat, keyframes};
    use crate::animation::StyledKeyframe;
    use std::time::Duration;

    #[test]
    fn animation_sequence_offsets_the_next_step() {
        let sequence = AnimationSequence::new()
            .then(Animation::new(Duration::from_millis(200)))
            .then(Animation::new(Duration::from_millis(300)))
            .with_overlap(Duration::from_millis(100));

        let animations = sequence.into_animations();
        assert_eq!(animations.len(), 2);
        assert_eq!(animations[0].scheduled_end(), Duration::from_millis(200));
        assert_eq!(animations[1].scheduled_end(), Duration::from_millis(400));
    }

    #[test]
    fn keyframes_interpolate_between_styles() {
        let frames = keyframes()
            .at(0.0, |frame| frame.scale(1.0).opacity(1.0))
            .at(1.0, |frame| frame.scale(1.2).opacity(0.5));

        let sample = frames.sample(0.5);
        assert_eq!(sample, StyledKeyframe::default().scale(1.1).opacity(0.75));
    }

    #[test]
    fn counted_animations_finish_after_the_requested_cycles() {
        let animation = Animation::new(Duration::from_millis(100)).repeat(Repeat::Count(2));

        assert!(!animation.sample(Duration::from_millis(150)).finished);
        assert!(animation.sample(Duration::from_millis(250)).finished);
    }
}

#[cfg(test)]
mod media_keyframe_tests {
    use super::*;

    #[test]
    fn empty_track_returns_default() {
        let track = KeyframeTrack::new();
        assert_eq!(track.sample(1.0, 42.0), 42.0);
        assert!(track.is_empty());
    }

    #[test]
    fn single_key_is_constant() {
        let track = KeyframeTrack::new().with_key(1.0, 5.0, KeyframeInterpolation::Hold);
        assert_eq!(track.sample(0.0, 0.0), 5.0);
        assert_eq!(track.sample(2.0, 0.0), 5.0);
    }

    #[test]
    fn linear_interpolates_between_keys() {
        let track = KeyframeTrack::new()
            .with_key(0.0, 0.0, KeyframeInterpolation::Eased(Easing::Linear))
            .with_key(1.0, 10.0, KeyframeInterpolation::Hold);
        assert!((track.sample(0.5, 0.0) - 5.0).abs() < 1e-5);
        assert!((track.sample(0.25, 0.0) - 2.5).abs() < 1e-5);
    }

    #[test]
    fn hold_steps_until_next_key() {
        let track = KeyframeTrack::new()
            .with_key(0.0, 1.0, KeyframeInterpolation::Hold)
            .with_key(1.0, 9.0, KeyframeInterpolation::Hold);
        assert_eq!(track.sample(0.5, 0.0), 1.0);
        assert_eq!(track.sample(0.99, 0.0), 1.0);
        assert_eq!(track.sample(1.0, 0.0), 9.0);
    }

    #[test]
    fn easing_differs_from_linear() {
        let eased = KeyframeTrack::new()
            .with_key(0.0, 0.0, KeyframeInterpolation::Eased(Easing::EaseIn))
            .with_key(1.0, 10.0, KeyframeInterpolation::Hold);
        assert!(eased.sample(0.5, 0.0) < 5.0);
    }

    #[test]
    fn clamps_outside_range() {
        let track = KeyframeTrack::new()
            .with_key(1.0, 2.0, KeyframeInterpolation::Eased(Easing::Linear))
            .with_key(3.0, 8.0, KeyframeInterpolation::Hold);
        assert_eq!(track.sample(-5.0, 0.0), 2.0);
        assert_eq!(track.sample(100.0, 0.0), 8.0);
    }

    #[test]
    fn out_of_order_insertion_stays_sorted() {
        let mut track = KeyframeTrack::new();
        track.insert(MediaKeyframe {
            time: 2.0,
            value: 20.0,
            interpolation: KeyframeInterpolation::Hold,
        });
        track.insert(MediaKeyframe {
            time: 0.0,
            value: 0.0,
            interpolation: KeyframeInterpolation::Eased(Easing::Linear),
        });
        track.insert(MediaKeyframe {
            time: 1.0,
            value: 10.0,
            interpolation: KeyframeInterpolation::Eased(Easing::Linear),
        });
        assert!((track.sample(0.5, 0.0) - 5.0).abs() < 1e-5);
        assert!((track.sample(1.5, 0.0) - 15.0).abs() < 1e-5);
        assert_eq!(track.len(), 3);
    }
}