Skip to main content

sui_animation/
lib.rs

1#![forbid(unsafe_code)]
2
3use std::{fmt, sync::Arc};
4
5use sui_core::{Color, ColorSpace, Point, Rect, Size, Transform, Vector};
6
7pub const ANIMATION_DOCUMENT_VERSION: u32 = 1;
8
9pub trait Interpolate: Sized {
10    fn interpolate(from: Self, to: Self, t: f32) -> Self;
11}
12
13impl Interpolate for f32 {
14    fn interpolate(from: Self, to: Self, t: f32) -> Self {
15        let t = t.clamp(0.0, 1.0);
16        // Endpoint-exact: `from + (to - from) * 1.0` accumulates float error
17        // and lands one bit away from `to`, so settled animations would never
18        // exactly reach their target value.
19        if t <= 0.0 {
20            return from;
21        }
22        if t >= 1.0 {
23            return to;
24        }
25        from + ((to - from) * t)
26    }
27}
28
29impl Interpolate for Point {
30    fn interpolate(from: Self, to: Self, t: f32) -> Self {
31        let t = t.clamp(0.0, 1.0);
32        Point::new(
33            f32::interpolate(from.x, to.x, t),
34            f32::interpolate(from.y, to.y, t),
35        )
36    }
37}
38
39impl Interpolate for Vector {
40    fn interpolate(from: Self, to: Self, t: f32) -> Self {
41        let t = t.clamp(0.0, 1.0);
42        Vector::new(
43            f32::interpolate(from.x, to.x, t),
44            f32::interpolate(from.y, to.y, t),
45        )
46    }
47}
48
49impl Interpolate for Size {
50    fn interpolate(from: Self, to: Self, t: f32) -> Self {
51        let t = t.clamp(0.0, 1.0);
52        Size::new(
53            f32::interpolate(from.width, to.width, t),
54            f32::interpolate(from.height, to.height, t),
55        )
56    }
57}
58
59impl Interpolate for Rect {
60    fn interpolate(from: Self, to: Self, t: f32) -> Self {
61        Rect::from_origin_size(
62            Point::interpolate(from.origin, to.origin, t),
63            Size::interpolate(from.size, to.size, t),
64        )
65    }
66}
67
68impl Interpolate for Transform {
69    fn interpolate(from: Self, to: Self, t: f32) -> Self {
70        let t = t.clamp(0.0, 1.0);
71        Transform::new(
72            f32::interpolate(from.xx, to.xx, t),
73            f32::interpolate(from.yx, to.yx, t),
74            f32::interpolate(from.xy, to.xy, t),
75            f32::interpolate(from.yy, to.yy, t),
76            f32::interpolate(from.dx, to.dx, t),
77            f32::interpolate(from.dy, to.dy, t),
78        )
79    }
80}
81
82impl Interpolate for Color {
83    fn interpolate(from: Self, to: Self, t: f32) -> Self {
84        let t = t.clamp(0.0, 1.0);
85        Color::new(
86            from.space,
87            f32::interpolate(from.red, to.red, t),
88            f32::interpolate(from.green, to.green, t),
89            f32::interpolate(from.blue, to.blue, t),
90            f32::interpolate(from.alpha, to.alpha, t),
91        )
92    }
93}
94
95#[derive(Debug, Clone, Copy, PartialEq, Default)]
96pub enum Easing {
97    #[default]
98    Linear,
99    EaseIn,
100    EaseOut,
101    EaseInOut,
102    CubicBezier {
103        x1: f32,
104        y1: f32,
105        x2: f32,
106        y2: f32,
107    },
108}
109
110impl Easing {
111    pub fn sample(self, t: f32) -> f32 {
112        let t = t.clamp(0.0, 1.0);
113        match self {
114            Self::Linear => t,
115            Self::EaseIn => t * t,
116            Self::EaseOut => 1.0 - (1.0 - t) * (1.0 - t),
117            Self::EaseInOut => {
118                if t < 0.5 {
119                    2.0 * t * t
120                } else {
121                    1.0 - ((-2.0 * t + 2.0).powi(2) * 0.5)
122                }
123            }
124            Self::CubicBezier { x1, y1, x2, y2 } => sample_cubic_bezier(x1, y1, x2, y2, t),
125        }
126    }
127}
128
129#[derive(Debug, Clone, Copy, PartialEq)]
130pub struct Transition<T> {
131    pub start: T,
132    pub end: T,
133    pub start_time: f64,
134    pub duration: f64,
135    pub easing: Easing,
136}
137
138impl<T> Transition<T>
139where
140    T: Copy + Interpolate,
141{
142    pub fn new(start: T, end: T, start_time: f64, duration: f64, easing: Easing) -> Self {
143        Self {
144            start,
145            end,
146            start_time,
147            duration: duration.max(0.0),
148            easing,
149        }
150    }
151
152    pub fn progress(&self, time: f64) -> f32 {
153        if self.duration <= f64::EPSILON {
154            return 1.0;
155        }
156        let elapsed = time - self.start_time;
157        // Snap to completion with a hair of tolerance: durations often
158        // originate as f32 theme tokens, so a fixed-step advance can land
159        // float dust short of `duration` and would otherwise sample at
160        // t = 1 - ε, leaving settled states one bit away from their target.
161        if elapsed >= self.duration * (1.0 - 1e-6) {
162            return 1.0;
163        }
164        (elapsed / self.duration).clamp(0.0, 1.0) as f32
165    }
166
167    pub fn sample(&self, time: f64) -> T {
168        T::interpolate(
169            self.start,
170            self.end,
171            self.easing.sample(self.progress(time)),
172        )
173    }
174
175    pub fn is_complete(&self, time: f64) -> bool {
176        self.progress(time) >= 1.0
177    }
178}
179
180#[derive(Debug, Clone, Copy, PartialEq)]
181pub struct SpringF32 {
182    pub value: f32,
183    pub velocity: f32,
184    pub stiffness: f32,
185    pub damping: f32,
186}
187
188impl SpringF32 {
189    pub fn new(value: f32) -> Self {
190        Self {
191            value,
192            velocity: 0.0,
193            stiffness: 180.0,
194            damping: 24.0,
195        }
196    }
197
198    pub fn with_config(mut self, stiffness: f32, damping: f32) -> Self {
199        self.stiffness = stiffness.max(0.0);
200        self.damping = damping.max(0.0);
201        self
202    }
203
204    pub fn step(&mut self, target: f32, delta: f64) -> f32 {
205        let dt = delta.max(0.0) as f32;
206        if dt <= f32::EPSILON {
207            return self.value;
208        }
209
210        let displacement = target - self.value;
211        let acceleration = (displacement * self.stiffness) - (self.velocity * self.damping);
212        self.velocity += acceleration * dt;
213        self.value += self.velocity * dt;
214        self.value
215    }
216}
217
218#[derive(Debug, Clone, Copy, PartialEq)]
219pub struct Blink {
220    pub period: f64,
221    pub duty_cycle: f32,
222    pub phase: f64,
223}
224
225impl Blink {
226    pub fn new(period: f64) -> Self {
227        Self {
228            period: period.max(f64::EPSILON),
229            duty_cycle: 0.5,
230            phase: 0.0,
231        }
232    }
233
234    pub fn with_duty_cycle(mut self, duty_cycle: f32) -> Self {
235        self.duty_cycle = duty_cycle.clamp(0.0, 1.0);
236        self
237    }
238
239    pub fn with_phase(mut self, phase: f64) -> Self {
240        self.phase = phase;
241        self
242    }
243
244    pub fn is_on(&self, time: f64) -> bool {
245        let cycle = ((time + self.phase).rem_euclid(self.period)) / self.period;
246        cycle < self.duty_cycle as f64
247    }
248}
249
250#[derive(Debug, Clone, Copy, PartialEq)]
251pub struct Pulse {
252    pub period: f64,
253    pub min: f32,
254    pub max: f32,
255    pub phase: f64,
256    pub easing: Easing,
257}
258
259impl Pulse {
260    pub fn new(period: f64, min: f32, max: f32) -> Self {
261        Self {
262            period: period.max(f64::EPSILON),
263            min,
264            max,
265            phase: 0.0,
266            easing: Easing::EaseInOut,
267        }
268    }
269
270    pub fn with_phase(mut self, phase: f64) -> Self {
271        self.phase = phase;
272        self
273    }
274
275    pub fn with_easing(mut self, easing: Easing) -> Self {
276        self.easing = easing;
277        self
278    }
279
280    pub fn sample(&self, time: f64) -> f32 {
281        let cycle = ((time + self.phase).rem_euclid(self.period)) / self.period;
282        let triangle = if cycle <= 0.5 {
283            (cycle * 2.0) as f32
284        } else {
285            ((1.0 - cycle) * 2.0) as f32
286        };
287        f32::interpolate(self.min, self.max, self.easing.sample(triangle))
288    }
289}
290
291#[derive(Debug, Clone, Copy, PartialEq)]
292pub struct AnimatedValue<T> {
293    start: T,
294    target: T,
295    current: T,
296    elapsed: f32,
297    duration: f32,
298    easing: Easing,
299    animating: bool,
300}
301
302impl<T> AnimatedValue<T>
303where
304    T: Interpolate + Copy,
305{
306    pub fn new(initial: T) -> Self {
307        Self {
308            start: initial,
309            target: initial,
310            current: initial,
311            elapsed: 0.0,
312            duration: 0.2,
313            easing: Easing::EaseInOut,
314            animating: false,
315        }
316    }
317
318    pub fn with_duration(mut self, seconds: f32) -> Self {
319        self.duration = seconds.max(0.0);
320        self
321    }
322
323    pub fn with_easing(mut self, easing: Easing) -> Self {
324        self.easing = easing;
325        self
326    }
327
328    pub fn set_duration(&mut self, seconds: f32) {
329        self.duration = seconds.max(0.0);
330    }
331
332    pub fn set_easing(&mut self, easing: Easing) {
333        self.easing = easing;
334    }
335
336    pub fn set_target(&mut self, target: T) {
337        self.target = target;
338        if self.duration <= f32::EPSILON {
339            self.start = target;
340            self.current = target;
341            self.elapsed = 0.0;
342            self.animating = false;
343            return;
344        }
345        self.start = self.current;
346        self.elapsed = 0.0;
347        self.animating = true;
348    }
349
350    pub fn jump_to(&mut self, value: T) {
351        self.start = value;
352        self.target = value;
353        self.current = value;
354        self.elapsed = 0.0;
355        self.animating = false;
356    }
357
358    pub fn tick(&mut self, delta_seconds: f32) -> bool {
359        if !self.animating {
360            return false;
361        }
362        self.elapsed += delta_seconds.max(0.0);
363        let progress = if self.duration <= f32::EPSILON {
364            1.0
365        } else {
366            (self.elapsed / self.duration).clamp(0.0, 1.0)
367        };
368        let eased = self.easing.sample(progress);
369        self.current = T::interpolate(self.start, self.target, eased);
370        if progress >= 1.0 {
371            self.current = self.target;
372            self.animating = false;
373            return false;
374        }
375        true
376    }
377
378    pub fn value(&self) -> T {
379        self.current
380    }
381
382    pub fn target(&self) -> T {
383        self.target
384    }
385
386    pub fn is_animating(&self) -> bool {
387        self.animating
388    }
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Hash)]
392pub struct AnimationTargetId(String);
393
394impl AnimationTargetId {
395    pub fn new(id: impl Into<String>) -> Self {
396        Self(id.into())
397    }
398
399    pub fn as_str(&self) -> &str {
400        &self.0
401    }
402}
403
404impl fmt::Display for AnimationTargetId {
405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
406        f.write_str(self.as_str())
407    }
408}
409
410impl From<&str> for AnimationTargetId {
411    fn from(value: &str) -> Self {
412        Self::new(value)
413    }
414}
415
416impl From<String> for AnimationTargetId {
417    fn from(value: String) -> Self {
418        Self::new(value)
419    }
420}
421
422#[derive(Debug, Clone, PartialEq, Eq, Hash)]
423pub struct AnimationPropertyPath(String);
424
425impl AnimationPropertyPath {
426    pub fn new(path: impl Into<String>) -> Self {
427        Self(path.into())
428    }
429
430    pub fn as_str(&self) -> &str {
431        &self.0
432    }
433}
434
435impl fmt::Display for AnimationPropertyPath {
436    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
437        f.write_str(self.as_str())
438    }
439}
440
441impl From<&str> for AnimationPropertyPath {
442    fn from(value: &str) -> Self {
443        Self::new(value)
444    }
445}
446
447impl From<String> for AnimationPropertyPath {
448    fn from(value: String) -> Self {
449        Self::new(value)
450    }
451}
452
453#[derive(Debug, Clone, PartialEq, Eq, Hash)]
454pub enum AnimationProperty {
455    LayerOpacity,
456    LayerTranslation,
457    FillColor,
458    Bounds,
459    Custom(AnimationPropertyPath),
460}
461
462impl AnimationProperty {
463    pub fn path(&self) -> &str {
464        match self {
465            Self::LayerOpacity => "layer.opacity",
466            Self::LayerTranslation => "layer.translation",
467            Self::FillColor => "fill.color",
468            Self::Bounds => "bounds",
469            Self::Custom(path) => path.as_str(),
470        }
471    }
472}
473
474#[derive(Debug, Clone, PartialEq, Eq, Hash)]
475pub struct AnimationBinding {
476    pub target: AnimationTargetId,
477    pub property: AnimationProperty,
478}
479
480impl AnimationBinding {
481    pub fn new(target: impl Into<AnimationTargetId>, property: AnimationProperty) -> Self {
482        Self {
483            target: target.into(),
484            property,
485        }
486    }
487}
488
489#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
490pub enum AnimationValueKind {
491    Scalar,
492    Point,
493    Vector,
494    Size,
495    Rect,
496    Color,
497    Transform,
498}
499
500#[derive(Debug, Clone, Copy, PartialEq)]
501pub enum AnimationValue {
502    Scalar(f32),
503    Point(Point),
504    Vector(Vector),
505    Size(Size),
506    Rect(Rect),
507    Color(Color),
508    Transform(Transform),
509}
510
511impl AnimationValue {
512    pub fn kind(self) -> AnimationValueKind {
513        match self {
514            Self::Scalar(_) => AnimationValueKind::Scalar,
515            Self::Point(_) => AnimationValueKind::Point,
516            Self::Vector(_) => AnimationValueKind::Vector,
517            Self::Size(_) => AnimationValueKind::Size,
518            Self::Rect(_) => AnimationValueKind::Rect,
519            Self::Color(_) => AnimationValueKind::Color,
520            Self::Transform(_) => AnimationValueKind::Transform,
521        }
522    }
523
524    pub fn as_scalar(self) -> Option<f32> {
525        match self {
526            Self::Scalar(value) => Some(value),
527            _ => None,
528        }
529    }
530
531    pub fn as_vector(self) -> Option<Vector> {
532        match self {
533            Self::Vector(value) => Some(value),
534            _ => None,
535        }
536    }
537
538    pub fn as_color(self) -> Option<Color> {
539        match self {
540            Self::Color(value) => Some(value),
541            _ => None,
542        }
543    }
544}
545
546impl Interpolate for AnimationValue {
547    fn interpolate(from: Self, to: Self, t: f32) -> Self {
548        match (from, to) {
549            (Self::Scalar(from), Self::Scalar(to)) => Self::Scalar(f32::interpolate(from, to, t)),
550            (Self::Point(from), Self::Point(to)) => Self::Point(Point::interpolate(from, to, t)),
551            (Self::Vector(from), Self::Vector(to)) => {
552                Self::Vector(Vector::interpolate(from, to, t))
553            }
554            (Self::Size(from), Self::Size(to)) => Self::Size(Size::interpolate(from, to, t)),
555            (Self::Rect(from), Self::Rect(to)) => Self::Rect(Rect::interpolate(from, to, t)),
556            (Self::Color(from), Self::Color(to)) => Self::Color(Color::interpolate(from, to, t)),
557            (Self::Transform(from), Self::Transform(to)) => {
558                Self::Transform(Transform::interpolate(from, to, t))
559            }
560            (from, to) => {
561                if t >= 1.0 {
562                    to
563                } else {
564                    from
565                }
566            }
567        }
568    }
569}
570
571impl From<f32> for AnimationValue {
572    fn from(value: f32) -> Self {
573        Self::Scalar(value)
574    }
575}
576
577impl From<Point> for AnimationValue {
578    fn from(value: Point) -> Self {
579        Self::Point(value)
580    }
581}
582
583impl From<Vector> for AnimationValue {
584    fn from(value: Vector) -> Self {
585        Self::Vector(value)
586    }
587}
588
589impl From<Size> for AnimationValue {
590    fn from(value: Size) -> Self {
591        Self::Size(value)
592    }
593}
594
595impl From<Rect> for AnimationValue {
596    fn from(value: Rect) -> Self {
597        Self::Rect(value)
598    }
599}
600
601impl From<Color> for AnimationValue {
602    fn from(value: Color) -> Self {
603        Self::Color(value)
604    }
605}
606
607impl From<Transform> for AnimationValue {
608    fn from(value: Transform) -> Self {
609        Self::Transform(value)
610    }
611}
612
613#[derive(Debug, Clone, Copy, PartialEq)]
614pub struct Keyframe<T> {
615    pub time: f64,
616    pub value: T,
617    pub easing: Easing,
618}
619
620impl<T> Keyframe<T> {
621    pub fn new(time: f64, value: T) -> Self {
622        Self {
623            time: time.max(0.0),
624            value,
625            easing: Easing::Linear,
626        }
627    }
628
629    pub fn with_easing(mut self, easing: Easing) -> Self {
630        self.easing = easing;
631        self
632    }
633}
634
635#[derive(Debug, Clone, PartialEq)]
636pub struct Track<T = AnimationValue> {
637    pub binding: AnimationBinding,
638    pub keyframes: Vec<Keyframe<T>>,
639    pub enabled: bool,
640}
641
642impl<T> Track<T> {
643    pub fn new(binding: AnimationBinding) -> Self {
644        Self {
645            binding,
646            keyframes: Vec::new(),
647            enabled: true,
648        }
649    }
650
651    pub fn with_keyframes(mut self, keyframes: impl IntoIterator<Item = Keyframe<T>>) -> Self {
652        self.keyframes.extend(keyframes);
653        self
654    }
655
656    pub fn push_keyframe(&mut self, keyframe: Keyframe<T>) {
657        self.keyframes.push(keyframe);
658    }
659
660    pub fn with_enabled(mut self, enabled: bool) -> Self {
661        self.enabled = enabled;
662        self
663    }
664}
665
666impl<T> Track<T>
667where
668    T: Copy + Interpolate,
669{
670    pub fn sample(&self, time: f64) -> Option<T> {
671        if !self.enabled || self.keyframes.is_empty() {
672            return None;
673        }
674
675        let mut first = &self.keyframes[0];
676        let mut last = &self.keyframes[0];
677        let mut previous = None;
678        let mut next = None;
679
680        for keyframe in &self.keyframes {
681            if keyframe.time < first.time {
682                first = keyframe;
683            }
684            if keyframe.time > last.time {
685                last = keyframe;
686            }
687            if keyframe.time <= time
688                && previous
689                    .map(|candidate: &Keyframe<T>| keyframe.time >= candidate.time)
690                    .unwrap_or(true)
691            {
692                previous = Some(keyframe);
693            }
694            if keyframe.time >= time
695                && next
696                    .map(|candidate: &Keyframe<T>| keyframe.time <= candidate.time)
697                    .unwrap_or(true)
698            {
699                next = Some(keyframe);
700            }
701        }
702
703        let Some(previous) = previous else {
704            return Some(first.value);
705        };
706        let Some(next) = next else {
707            return Some(last.value);
708        };
709        if (next.time - previous.time).abs() <= f64::EPSILON {
710            return Some(next.value);
711        }
712
713        let progress = ((time - previous.time) / (next.time - previous.time)).clamp(0.0, 1.0);
714        Some(T::interpolate(
715            previous.value,
716            next.value,
717            previous.easing.sample(progress as f32),
718        ))
719    }
720}
721
722fn sample_sorted_keyframes<T>(keyframes: &[Keyframe<T>], time: f64) -> Option<T>
723where
724    T: Copy + Interpolate,
725{
726    let first = keyframes.first()?;
727    let last = keyframes.last()?;
728    if time <= first.time {
729        return Some(first.value);
730    }
731    if time >= last.time {
732        return Some(last.value);
733    }
734
735    let next_index = keyframes.partition_point(|keyframe| keyframe.time < time);
736    let previous_index = next_index.saturating_sub(1);
737    let previous = &keyframes[previous_index];
738    let next = &keyframes[next_index];
739    if (next.time - previous.time).abs() <= f64::EPSILON {
740        return Some(next.value);
741    }
742
743    let progress = ((time - previous.time) / (next.time - previous.time)).clamp(0.0, 1.0);
744    Some(T::interpolate(
745        previous.value,
746        next.value,
747        previous.easing.sample(progress as f32),
748    ))
749}
750
751#[derive(Debug, Clone, PartialEq)]
752pub struct Clip<T = AnimationValue> {
753    pub id: String,
754    pub start_time: f64,
755    pub duration: f64,
756    pub tracks: Vec<Track<T>>,
757    pub enabled: bool,
758}
759
760impl<T> Clip<T> {
761    pub fn new(id: impl Into<String>, start_time: f64, duration: f64) -> Self {
762        Self {
763            id: id.into(),
764            start_time: start_time.max(0.0),
765            duration: duration.max(0.0),
766            tracks: Vec::new(),
767            enabled: true,
768        }
769    }
770
771    pub fn with_track(mut self, track: Track<T>) -> Self {
772        self.tracks.push(track);
773        self
774    }
775
776    pub fn push_track(&mut self, track: Track<T>) {
777        self.tracks.push(track);
778    }
779
780    pub fn end_time(&self) -> f64 {
781        self.start_time + self.duration
782    }
783
784    pub fn contains_time(&self, time: f64) -> bool {
785        self.enabled && time >= self.start_time && time <= self.end_time()
786    }
787}
788
789impl<T> Clip<T>
790where
791    T: Copy + Interpolate,
792{
793    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
794        let mut buffer = SampleBuffer::new();
795        self.sample_into(time, &mut buffer);
796        buffer.into_samples()
797    }
798
799    pub fn sample_into<'a>(
800        &self,
801        time: f64,
802        samples: &'a mut SampleBuffer<T>,
803    ) -> SampleBatch<'a, T> {
804        samples.clear();
805        self.append_samples(time, samples.samples_mut());
806        samples.batch()
807    }
808
809    fn append_samples(&self, time: f64, samples: &mut Vec<SampledAnimationValue<T>>) {
810        if !self.contains_time(time) {
811            return;
812        }
813
814        let local_time = time - self.start_time;
815        for track in &self.tracks {
816            if let Some(value) = track.sample(local_time) {
817                samples.push(SampledAnimationValue {
818                    clip_id: self.id.clone(),
819                    binding: track.binding.clone(),
820                    time,
821                    value,
822                });
823            }
824        }
825    }
826}
827
828#[derive(Debug, Clone, PartialEq)]
829pub struct Timeline<T = AnimationValue> {
830    pub duration: f64,
831    pub clips: Vec<Clip<T>>,
832}
833
834impl<T> Timeline<T> {
835    pub fn new(duration: f64) -> Self {
836        Self {
837            duration: duration.max(0.0),
838            clips: Vec::new(),
839        }
840    }
841
842    pub fn with_clip(mut self, clip: Clip<T>) -> Self {
843        self.clips.push(clip);
844        self
845    }
846
847    pub fn push_clip(&mut self, clip: Clip<T>) {
848        self.clips.push(clip);
849    }
850}
851
852impl<T> Default for Timeline<T> {
853    fn default() -> Self {
854        Self::new(0.0)
855    }
856}
857
858impl<T> Timeline<T>
859where
860    T: Copy + Interpolate,
861{
862    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
863        let mut buffer = SampleBuffer::new();
864        self.sample_into(time, &mut buffer);
865        buffer.into_samples()
866    }
867
868    pub fn sample_into<'a>(
869        &self,
870        time: f64,
871        samples: &'a mut SampleBuffer<T>,
872    ) -> SampleBatch<'a, T> {
873        let clamped_time = time.clamp(0.0, self.duration.max(0.0));
874        samples.clear();
875        let samples_vec = samples.samples_mut();
876        for clip in &self.clips {
877            clip.append_samples(clamped_time, samples_vec);
878        }
879        samples.batch()
880    }
881}
882
883impl<T> Timeline<T>
884where
885    T: Clone,
886{
887    pub fn compile(&self) -> CompiledTimeline<T> {
888        CompiledTimeline::from_timeline(self)
889    }
890
891    pub fn compile_shared(&self) -> SharedCompiledTimeline<T> {
892        self.compile().into_shared()
893    }
894}
895
896#[derive(Debug, Clone, PartialEq)]
897pub struct CompiledTimeline<T = AnimationValue> {
898    duration: f64,
899    clips: Vec<CompiledClip<T>>,
900    sample_capacity: usize,
901}
902
903pub type SharedCompiledTimeline<T = AnimationValue> = Arc<CompiledTimeline<T>>;
904
905impl<T> CompiledTimeline<T>
906where
907    T: Clone,
908{
909    pub fn from_timeline(timeline: &Timeline<T>) -> Self {
910        let clips = timeline
911            .clips
912            .iter()
913            .filter(|clip| clip.enabled)
914            .filter_map(CompiledClip::from_clip)
915            .collect::<Vec<_>>();
916        let sample_capacity = clips.iter().map(|clip| clip.tracks.len()).sum();
917        Self {
918            duration: timeline.duration.max(0.0),
919            clips,
920            sample_capacity,
921        }
922    }
923}
924
925impl<T> CompiledTimeline<T> {
926    pub fn into_shared(self) -> SharedCompiledTimeline<T> {
927        Arc::new(self)
928    }
929
930    pub fn duration(&self) -> f64 {
931        self.duration
932    }
933
934    pub fn clips(&self) -> &[CompiledClip<T>] {
935        &self.clips
936    }
937
938    pub fn sample_capacity(&self) -> usize {
939        self.sample_capacity
940    }
941}
942
943impl<T> CompiledTimeline<T>
944where
945    T: Clone,
946{
947    pub fn to_shared(&self) -> SharedCompiledTimeline<T> {
948        Arc::new(self.clone())
949    }
950
951    pub fn player(&self) -> AnimationPlayer<T> {
952        AnimationPlayer::new(self.to_shared())
953    }
954}
955
956impl<T> CompiledTimeline<T>
957where
958    T: Copy + Interpolate,
959{
960    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
961        let mut buffer = SampleBuffer::with_capacity(self.sample_capacity);
962        self.sample_into(time, &mut buffer);
963        buffer.into_samples()
964    }
965
966    pub fn sample_into<'a>(
967        &self,
968        time: f64,
969        samples: &'a mut SampleBuffer<T>,
970    ) -> SampleBatch<'a, T> {
971        let clamped_time = time.clamp(0.0, self.duration);
972        samples.clear();
973        samples.reserve_capacity(self.sample_capacity);
974        let samples_vec = samples.samples_mut();
975        for clip in &self.clips {
976            clip.append_samples(clamped_time, samples_vec);
977        }
978        samples.batch()
979    }
980}
981
982impl<T> From<&Timeline<T>> for CompiledTimeline<T>
983where
984    T: Clone,
985{
986    fn from(timeline: &Timeline<T>) -> Self {
987        Self::from_timeline(timeline)
988    }
989}
990
991#[derive(Debug, Clone, PartialEq)]
992pub struct CompiledClip<T = AnimationValue> {
993    id: String,
994    start_time: f64,
995    duration: f64,
996    tracks: Vec<CompiledTrack<T>>,
997}
998
999impl<T> CompiledClip<T>
1000where
1001    T: Clone,
1002{
1003    fn from_clip(clip: &Clip<T>) -> Option<Self> {
1004        let tracks = clip
1005            .tracks
1006            .iter()
1007            .filter(|track| track.enabled && !track.keyframes.is_empty())
1008            .map(CompiledTrack::from_track)
1009            .collect::<Vec<_>>();
1010        if tracks.is_empty() {
1011            return None;
1012        }
1013
1014        Some(Self {
1015            id: clip.id.clone(),
1016            start_time: clip.start_time,
1017            duration: clip.duration,
1018            tracks,
1019        })
1020    }
1021}
1022
1023impl<T> CompiledClip<T> {
1024    pub fn id(&self) -> &str {
1025        &self.id
1026    }
1027
1028    pub fn start_time(&self) -> f64 {
1029        self.start_time
1030    }
1031
1032    pub fn duration(&self) -> f64 {
1033        self.duration
1034    }
1035
1036    pub fn end_time(&self) -> f64 {
1037        self.start_time + self.duration
1038    }
1039
1040    pub fn tracks(&self) -> &[CompiledTrack<T>] {
1041        &self.tracks
1042    }
1043
1044    pub fn contains_time(&self, time: f64) -> bool {
1045        time >= self.start_time && time <= self.end_time()
1046    }
1047}
1048
1049impl<T> CompiledClip<T>
1050where
1051    T: Copy + Interpolate,
1052{
1053    pub fn sample(&self, time: f64) -> Vec<SampledAnimationValue<T>> {
1054        let mut buffer = SampleBuffer::new();
1055        self.sample_into(time, &mut buffer);
1056        buffer.into_samples()
1057    }
1058
1059    pub fn sample_into<'a>(
1060        &self,
1061        time: f64,
1062        samples: &'a mut SampleBuffer<T>,
1063    ) -> SampleBatch<'a, T> {
1064        samples.clear();
1065        self.append_samples(time, samples.samples_mut());
1066        samples.batch()
1067    }
1068
1069    fn append_samples(&self, time: f64, samples: &mut Vec<SampledAnimationValue<T>>) {
1070        if !self.contains_time(time) {
1071            return;
1072        }
1073
1074        let local_time = time - self.start_time;
1075        for track in &self.tracks {
1076            if let Some(value) = track.sample(local_time) {
1077                samples.push(SampledAnimationValue {
1078                    clip_id: self.id.clone(),
1079                    binding: track.binding.clone(),
1080                    time,
1081                    value,
1082                });
1083            }
1084        }
1085    }
1086}
1087
1088#[derive(Debug, Clone, PartialEq)]
1089pub struct CompiledTrack<T = AnimationValue> {
1090    binding: AnimationBinding,
1091    keyframes: Vec<Keyframe<T>>,
1092}
1093
1094impl<T> CompiledTrack<T>
1095where
1096    T: Clone,
1097{
1098    fn from_track(track: &Track<T>) -> Self {
1099        let mut keyframes = track.keyframes.clone();
1100        keyframes.sort_by(|left, right| left.time.total_cmp(&right.time));
1101        Self {
1102            binding: track.binding.clone(),
1103            keyframes,
1104        }
1105    }
1106}
1107
1108impl<T> CompiledTrack<T> {
1109    pub fn binding(&self) -> &AnimationBinding {
1110        &self.binding
1111    }
1112
1113    pub fn keyframes(&self) -> &[Keyframe<T>] {
1114        &self.keyframes
1115    }
1116}
1117
1118impl<T> CompiledTrack<T>
1119where
1120    T: Copy + Interpolate,
1121{
1122    pub fn sample(&self, time: f64) -> Option<T> {
1123        sample_sorted_keyframes(&self.keyframes, time)
1124    }
1125}
1126
1127#[derive(Debug, Clone, PartialEq)]
1128pub struct SampledAnimationValue<T = AnimationValue> {
1129    pub clip_id: String,
1130    pub binding: AnimationBinding,
1131    pub time: f64,
1132    pub value: T,
1133}
1134
1135#[derive(Debug, Clone, PartialEq, Default)]
1136pub struct SampleBuffer<T = AnimationValue> {
1137    samples: Vec<SampledAnimationValue<T>>,
1138}
1139
1140impl<T> SampleBuffer<T> {
1141    pub fn new() -> Self {
1142        Self {
1143            samples: Vec::new(),
1144        }
1145    }
1146
1147    pub fn with_capacity(capacity: usize) -> Self {
1148        Self {
1149            samples: Vec::with_capacity(capacity),
1150        }
1151    }
1152
1153    pub fn len(&self) -> usize {
1154        self.samples.len()
1155    }
1156
1157    pub fn is_empty(&self) -> bool {
1158        self.samples.is_empty()
1159    }
1160
1161    pub fn capacity(&self) -> usize {
1162        self.samples.capacity()
1163    }
1164
1165    pub fn clear(&mut self) {
1166        self.samples.clear();
1167    }
1168
1169    pub fn reserve_capacity(&mut self, target_capacity: usize) {
1170        self.samples
1171            .reserve(target_capacity.saturating_sub(self.samples.capacity()));
1172    }
1173
1174    pub fn samples(&self) -> &[SampledAnimationValue<T>] {
1175        &self.samples
1176    }
1177
1178    pub fn batch(&self) -> SampleBatch<'_, T> {
1179        SampleBatch {
1180            samples: &self.samples,
1181        }
1182    }
1183
1184    pub fn into_samples(self) -> Vec<SampledAnimationValue<T>> {
1185        self.samples
1186    }
1187
1188    fn samples_mut(&mut self) -> &mut Vec<SampledAnimationValue<T>> {
1189        &mut self.samples
1190    }
1191}
1192
1193impl<T> AsRef<[SampledAnimationValue<T>]> for SampleBuffer<T> {
1194    fn as_ref(&self) -> &[SampledAnimationValue<T>] {
1195        self.samples()
1196    }
1197}
1198
1199#[derive(Debug, Clone, Copy, PartialEq)]
1200pub struct SampleBatch<'a, T = AnimationValue> {
1201    samples: &'a [SampledAnimationValue<T>],
1202}
1203
1204impl<'a, T> SampleBatch<'a, T> {
1205    pub fn samples(self) -> &'a [SampledAnimationValue<T>] {
1206        self.samples
1207    }
1208
1209    pub fn iter(self) -> std::slice::Iter<'a, SampledAnimationValue<T>> {
1210        self.samples.iter()
1211    }
1212
1213    pub fn len(self) -> usize {
1214        self.samples.len()
1215    }
1216
1217    pub fn is_empty(self) -> bool {
1218        self.samples.is_empty()
1219    }
1220}
1221
1222impl<'a, T> IntoIterator for SampleBatch<'a, T> {
1223    type Item = &'a SampledAnimationValue<T>;
1224    type IntoIter = std::slice::Iter<'a, SampledAnimationValue<T>>;
1225
1226    fn into_iter(self) -> Self::IntoIter {
1227        self.iter()
1228    }
1229}
1230
1231#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1232pub enum LoopMode {
1233    #[default]
1234    Once,
1235    Repeat,
1236}
1237
1238#[derive(Debug, Clone, Copy, PartialEq)]
1239pub struct PlaybackState {
1240    pub playhead: f64,
1241    pub playback_rate: f64,
1242    pub playing: bool,
1243    pub loop_mode: LoopMode,
1244}
1245
1246impl Default for PlaybackState {
1247    fn default() -> Self {
1248        Self {
1249            playhead: 0.0,
1250            playback_rate: 1.0,
1251            playing: false,
1252            loop_mode: LoopMode::Once,
1253        }
1254    }
1255}
1256
1257impl PlaybackState {
1258    pub fn play(&mut self) {
1259        self.playing = true;
1260    }
1261
1262    pub fn pause(&mut self) {
1263        self.playing = false;
1264    }
1265
1266    pub fn stop(&mut self) {
1267        self.playing = false;
1268        self.playhead = 0.0;
1269    }
1270
1271    pub fn seek(&mut self, time: f64, duration: f64) {
1272        self.playhead = time.clamp(0.0, duration.max(0.0));
1273    }
1274
1275    pub fn tick(&mut self, delta_seconds: f64, duration: f64) -> bool {
1276        if !self.playing {
1277            return false;
1278        }
1279
1280        let previous_time = self.playhead;
1281        let duration = duration.max(0.0);
1282        if duration <= f64::EPSILON {
1283            self.playhead = 0.0;
1284            self.playing = false;
1285            return previous_time != self.playhead;
1286        }
1287
1288        self.playhead += delta_seconds.max(0.0) * self.playback_rate;
1289        if self.playhead > duration {
1290            match self.loop_mode {
1291                LoopMode::Once => {
1292                    self.playhead = duration;
1293                    self.playing = false;
1294                }
1295                LoopMode::Repeat => {
1296                    self.playhead = self.playhead.rem_euclid(duration);
1297                }
1298            }
1299        } else if self.playhead < 0.0 {
1300            match self.loop_mode {
1301                LoopMode::Once => {
1302                    self.playhead = 0.0;
1303                    self.playing = false;
1304                }
1305                LoopMode::Repeat => {
1306                    self.playhead = self.playhead.rem_euclid(duration);
1307                }
1308            }
1309        }
1310
1311        previous_time != self.playhead
1312    }
1313}
1314
1315#[derive(Debug, Clone, PartialEq)]
1316pub struct AnimationPlayer<T = AnimationValue> {
1317    timeline: SharedCompiledTimeline<T>,
1318    playback: PlaybackState,
1319}
1320
1321impl<T> AnimationPlayer<T> {
1322    pub fn new(timeline: SharedCompiledTimeline<T>) -> Self {
1323        Self {
1324            timeline,
1325            playback: PlaybackState::default(),
1326        }
1327    }
1328
1329    pub fn from_compiled(timeline: CompiledTimeline<T>) -> Self {
1330        Self::new(timeline.into_shared())
1331    }
1332
1333    pub fn timeline(&self) -> &CompiledTimeline<T> {
1334        self.timeline.as_ref()
1335    }
1336
1337    pub fn shared_timeline(&self) -> SharedCompiledTimeline<T> {
1338        Arc::clone(&self.timeline)
1339    }
1340
1341    pub fn playback(&self) -> PlaybackState {
1342        self.playback
1343    }
1344
1345    pub fn playback_mut(&mut self) -> &mut PlaybackState {
1346        &mut self.playback
1347    }
1348
1349    pub fn with_loop_mode(mut self, loop_mode: LoopMode) -> Self {
1350        self.playback.loop_mode = loop_mode;
1351        self
1352    }
1353
1354    pub fn repeat(self) -> Self {
1355        self.with_loop_mode(LoopMode::Repeat)
1356    }
1357
1358    pub fn once(self) -> Self {
1359        self.with_loop_mode(LoopMode::Once)
1360    }
1361
1362    pub fn with_playback_rate(mut self, playback_rate: f64) -> Self {
1363        self.playback.playback_rate = playback_rate;
1364        self
1365    }
1366
1367    pub fn play(&mut self) {
1368        self.playback.play();
1369    }
1370
1371    pub fn pause(&mut self) {
1372        self.playback.pause();
1373    }
1374
1375    pub fn stop(&mut self) {
1376        self.playback.stop();
1377    }
1378
1379    pub fn seek(&mut self, time: f64) {
1380        self.playback.seek(time, self.timeline.duration());
1381    }
1382}
1383
1384impl<T> AnimationPlayer<T>
1385where
1386    T: Copy + Interpolate,
1387{
1388    pub fn sample(&self) -> Vec<SampledAnimationValue<T>> {
1389        self.timeline.sample(self.playback.playhead)
1390    }
1391
1392    pub fn sample_into<'a>(&self, samples: &'a mut SampleBuffer<T>) -> SampleBatch<'a, T> {
1393        self.timeline.sample_into(self.playback.playhead, samples)
1394    }
1395
1396    pub fn tick_into<'a>(
1397        &mut self,
1398        delta_seconds: f64,
1399        samples: &'a mut SampleBuffer<T>,
1400    ) -> AnimationTick<'a, T> {
1401        let advanced = self.playback.tick(delta_seconds, self.timeline.duration());
1402        let samples = self.timeline.sample_into(self.playback.playhead, samples);
1403        AnimationTick {
1404            samples,
1405            playback: self.playback,
1406            advanced,
1407            should_continue: self.playback.playing,
1408        }
1409    }
1410}
1411
1412#[derive(Debug, Clone, Copy, PartialEq)]
1413pub struct AnimationTick<'a, T = AnimationValue> {
1414    pub samples: SampleBatch<'a, T>,
1415    pub playback: PlaybackState,
1416    pub advanced: bool,
1417    pub should_continue: bool,
1418}
1419
1420impl<'a, T> AnimationTick<'a, T> {
1421    pub fn samples(self) -> SampleBatch<'a, T> {
1422        self.samples
1423    }
1424
1425    pub fn sample_values(self) -> &'a [SampledAnimationValue<T>] {
1426        self.samples.samples()
1427    }
1428}
1429
1430#[derive(Debug, Clone, PartialEq)]
1431pub struct AnimationDocument {
1432    pub version: u32,
1433    pub name: String,
1434    pub timeline: Timeline,
1435}
1436
1437impl AnimationDocument {
1438    pub fn new(name: impl Into<String>, timeline: Timeline) -> Self {
1439        Self {
1440            version: ANIMATION_DOCUMENT_VERSION,
1441            name: name.into(),
1442            timeline,
1443        }
1444    }
1445
1446    pub fn to_document_format(&self) -> String {
1447        let mut output = String::new();
1448        output.push_str("sui-animation-document\t");
1449        output.push_str(&self.version.to_string());
1450        output.push('\n');
1451        output.push_str("name\t");
1452        output.push_str(&escape_document_field(&self.name));
1453        output.push('\n');
1454        output.push_str("duration\t");
1455        output.push_str(&format_f64(self.timeline.duration));
1456        output.push('\n');
1457
1458        for clip in &self.timeline.clips {
1459            output.push_str("clip\t");
1460            output.push_str(&escape_document_field(&clip.id));
1461            output.push('\t');
1462            output.push_str(&format_f64(clip.start_time));
1463            output.push('\t');
1464            output.push_str(&format_f64(clip.duration));
1465            output.push('\t');
1466            output.push_str(format_bool(clip.enabled));
1467            output.push('\n');
1468
1469            for track in &clip.tracks {
1470                output.push_str("track\t");
1471                output.push_str(&escape_document_field(track.binding.target.as_str()));
1472                output.push('\t');
1473                output.push_str(&escape_document_field(track.binding.property.path()));
1474                output.push('\t');
1475                output.push_str(format_bool(track.enabled));
1476                output.push('\n');
1477
1478                for keyframe in &track.keyframes {
1479                    output.push_str("key\t");
1480                    output.push_str(&format_f64(keyframe.time));
1481                    output.push('\t');
1482                    output.push_str(&format_easing(keyframe.easing));
1483                    output.push('\t');
1484                    output.push_str(&format_animation_value(keyframe.value));
1485                    output.push('\n');
1486                }
1487
1488                output.push_str("endtrack\n");
1489            }
1490
1491            output.push_str("endclip\n");
1492        }
1493
1494        output
1495    }
1496
1497    pub fn from_document_format(input: &str) -> Result<Self, AnimationDocumentFormatError> {
1498        AnimationDocumentFormatParser::new(input).parse()
1499    }
1500}
1501
1502impl Default for AnimationDocument {
1503    fn default() -> Self {
1504        Self::new("Untitled animation", Timeline::default())
1505    }
1506}
1507
1508#[derive(Debug, Clone, PartialEq, Eq)]
1509pub struct AnimationDocumentFormatError {
1510    pub line: Option<usize>,
1511    pub message: String,
1512}
1513
1514impl AnimationDocumentFormatError {
1515    fn new(line: Option<usize>, message: impl Into<String>) -> Self {
1516        Self {
1517            line,
1518            message: message.into(),
1519        }
1520    }
1521}
1522
1523impl fmt::Display for AnimationDocumentFormatError {
1524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1525        match self.line {
1526            Some(line) => write!(
1527                f,
1528                "animation document format error on line {line}: {}",
1529                self.message
1530            ),
1531            None => write!(f, "animation document format error: {}", self.message),
1532        }
1533    }
1534}
1535
1536impl std::error::Error for AnimationDocumentFormatError {}
1537
1538#[derive(Debug, Clone, Copy, PartialEq)]
1539pub struct TimelineSnap {
1540    pub enabled: bool,
1541    pub interval: f64,
1542}
1543
1544impl TimelineSnap {
1545    pub fn new(interval: f64) -> Self {
1546        Self {
1547            enabled: true,
1548            interval: interval.max(f64::EPSILON),
1549        }
1550    }
1551
1552    pub fn disabled() -> Self {
1553        Self {
1554            enabled: false,
1555            interval: 1.0 / 60.0,
1556        }
1557    }
1558
1559    pub fn snap_time(self, time: f64) -> f64 {
1560        if !self.enabled {
1561            return time.max(0.0);
1562        }
1563        ((time.max(0.0) / self.interval).round() * self.interval).max(0.0)
1564    }
1565}
1566
1567impl Default for TimelineSnap {
1568    fn default() -> Self {
1569        Self::new(1.0 / 24.0)
1570    }
1571}
1572
1573#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1574pub struct KeyframeSelection {
1575    pub clip_index: usize,
1576    pub track_index: usize,
1577    pub keyframe_index: usize,
1578}
1579
1580#[derive(Debug, Clone, PartialEq, Eq, Default)]
1581pub struct AnimationSelection {
1582    pub clip_index: Option<usize>,
1583    pub track_index: Option<usize>,
1584    pub keyframes: Vec<KeyframeSelection>,
1585}
1586
1587#[derive(Debug, Clone, PartialEq)]
1588pub enum AnimationEditorCommand {
1589    SetPlayhead(f64),
1590    SetZoom(f32),
1591    SetScroll(f32),
1592    SetSnapping(TimelineSnap),
1593    ClearSelection,
1594    SelectClip(usize),
1595    SelectTrack {
1596        clip_index: usize,
1597        track_index: usize,
1598    },
1599    SelectKeyframe(KeyframeSelection),
1600    AddKeyframe {
1601        clip_index: usize,
1602        track_index: usize,
1603        keyframe: Keyframe<AnimationValue>,
1604    },
1605    UpdateKeyframeEasing {
1606        selection: KeyframeSelection,
1607        easing: Easing,
1608    },
1609    RemoveKeyframe(KeyframeSelection),
1610}
1611
1612#[derive(Debug, Clone, PartialEq)]
1613pub struct AnimationEditorState {
1614    pub document: AnimationDocument,
1615    pub playback: PlaybackState,
1616    pub selection: AnimationSelection,
1617    pub zoom: f32,
1618    pub scroll: f32,
1619    pub snap: TimelineSnap,
1620    undo_stack: Vec<AnimationDocument>,
1621    redo_stack: Vec<AnimationDocument>,
1622}
1623
1624impl AnimationEditorState {
1625    pub fn new(document: AnimationDocument) -> Self {
1626        Self {
1627            document,
1628            playback: PlaybackState::default(),
1629            selection: AnimationSelection::default(),
1630            zoom: 1.0,
1631            scroll: 0.0,
1632            snap: TimelineSnap::default(),
1633            undo_stack: Vec::new(),
1634            redo_stack: Vec::new(),
1635        }
1636    }
1637
1638    pub fn undo_len(&self) -> usize {
1639        self.undo_stack.len()
1640    }
1641
1642    pub fn redo_len(&self) -> usize {
1643        self.redo_stack.len()
1644    }
1645
1646    pub fn can_undo(&self) -> bool {
1647        !self.undo_stack.is_empty()
1648    }
1649
1650    pub fn can_redo(&self) -> bool {
1651        !self.redo_stack.is_empty()
1652    }
1653
1654    pub fn apply_command(&mut self, command: AnimationEditorCommand) -> bool {
1655        match command {
1656            AnimationEditorCommand::SetPlayhead(time) => {
1657                self.playback.seek(time, self.document.timeline.duration);
1658                true
1659            }
1660            AnimationEditorCommand::SetZoom(zoom) => {
1661                self.zoom = zoom.max(0.05);
1662                true
1663            }
1664            AnimationEditorCommand::SetScroll(scroll) => {
1665                self.scroll = scroll.max(0.0);
1666                true
1667            }
1668            AnimationEditorCommand::SetSnapping(snap) => {
1669                self.snap = snap;
1670                true
1671            }
1672            AnimationEditorCommand::ClearSelection => {
1673                self.selection = AnimationSelection::default();
1674                true
1675            }
1676            AnimationEditorCommand::SelectClip(clip_index) => {
1677                self.selection.clip_index = Some(clip_index);
1678                self.selection.track_index = None;
1679                self.selection.keyframes.clear();
1680                true
1681            }
1682            AnimationEditorCommand::SelectTrack {
1683                clip_index,
1684                track_index,
1685            } => {
1686                self.selection.clip_index = Some(clip_index);
1687                self.selection.track_index = Some(track_index);
1688                self.selection.keyframes.clear();
1689                true
1690            }
1691            AnimationEditorCommand::SelectKeyframe(selection) => {
1692                self.selection.clip_index = Some(selection.clip_index);
1693                self.selection.track_index = Some(selection.track_index);
1694                if !self.selection.keyframes.contains(&selection) {
1695                    self.selection.keyframes.push(selection);
1696                }
1697                true
1698            }
1699            AnimationEditorCommand::AddKeyframe {
1700                clip_index,
1701                track_index,
1702                mut keyframe,
1703            } => {
1704                let Some(track) = self
1705                    .document
1706                    .timeline
1707                    .clips
1708                    .get(clip_index)
1709                    .and_then(|clip| clip.tracks.get(track_index))
1710                else {
1711                    return false;
1712                };
1713                let mut updated_track = track.clone();
1714                keyframe.time = self.snap.snap_time(keyframe.time);
1715                updated_track.push_keyframe(keyframe);
1716
1717                self.push_undo_snapshot();
1718                self.document.timeline.clips[clip_index].tracks[track_index] = updated_track;
1719                self.redo_stack.clear();
1720                true
1721            }
1722            AnimationEditorCommand::UpdateKeyframeEasing { selection, easing } => {
1723                let Some(track) = self
1724                    .document
1725                    .timeline
1726                    .clips
1727                    .get(selection.clip_index)
1728                    .and_then(|clip| clip.tracks.get(selection.track_index))
1729                else {
1730                    return false;
1731                };
1732                let Some(keyframe) = track.keyframes.get(selection.keyframe_index) else {
1733                    return false;
1734                };
1735
1736                let mut updated_track = track.clone();
1737                let mut updated_keyframe = *keyframe;
1738                updated_keyframe.easing = easing;
1739                updated_track.keyframes[selection.keyframe_index] = updated_keyframe;
1740
1741                self.push_undo_snapshot();
1742                self.document.timeline.clips[selection.clip_index].tracks[selection.track_index] =
1743                    updated_track;
1744                self.redo_stack.clear();
1745                true
1746            }
1747            AnimationEditorCommand::RemoveKeyframe(selection) => {
1748                let Some(track) = self
1749                    .document
1750                    .timeline
1751                    .clips
1752                    .get(selection.clip_index)
1753                    .and_then(|clip| clip.tracks.get(selection.track_index))
1754                else {
1755                    return false;
1756                };
1757                if selection.keyframe_index >= track.keyframes.len() {
1758                    return false;
1759                }
1760
1761                let mut updated_track = track.clone();
1762                updated_track.keyframes.remove(selection.keyframe_index);
1763
1764                self.push_undo_snapshot();
1765                self.document.timeline.clips[selection.clip_index].tracks[selection.track_index] =
1766                    updated_track;
1767                self.selection
1768                    .keyframes
1769                    .retain(|selected| *selected != selection);
1770                self.redo_stack.clear();
1771                true
1772            }
1773        }
1774    }
1775
1776    pub fn undo(&mut self) -> bool {
1777        let Some(previous) = self.undo_stack.pop() else {
1778            return false;
1779        };
1780        self.redo_stack.push(self.document.clone());
1781        self.document = previous;
1782        true
1783    }
1784
1785    pub fn redo(&mut self) -> bool {
1786        let Some(next) = self.redo_stack.pop() else {
1787            return false;
1788        };
1789        self.undo_stack.push(self.document.clone());
1790        self.document = next;
1791        true
1792    }
1793
1794    fn push_undo_snapshot(&mut self) {
1795        self.undo_stack.push(self.document.clone());
1796    }
1797}
1798
1799impl Default for AnimationEditorState {
1800    fn default() -> Self {
1801        Self::new(AnimationDocument::default())
1802    }
1803}
1804
1805struct AnimationDocumentFormatParser<'a> {
1806    input: &'a str,
1807}
1808
1809impl<'a> AnimationDocumentFormatParser<'a> {
1810    fn new(input: &'a str) -> Self {
1811        Self { input }
1812    }
1813
1814    fn parse(self) -> Result<AnimationDocument, AnimationDocumentFormatError> {
1815        let mut version = None;
1816        let mut name = None;
1817        let mut duration = None;
1818        let mut clips = Vec::new();
1819        let mut current_clip: Option<Clip> = None;
1820        let mut current_track: Option<Track> = None;
1821
1822        for (line_index, raw_line) in self.input.lines().enumerate() {
1823            let line_no = line_index + 1;
1824            let line = raw_line.trim_end_matches('\r');
1825            if line.is_empty() {
1826                continue;
1827            }
1828
1829            let fields = line.split('\t').collect::<Vec<_>>();
1830            match fields.first().copied().unwrap_or_default() {
1831                "sui-animation-document" => {
1832                    expect_field_count(line_no, &fields, 2)?;
1833                    if version.is_some() {
1834                        return Err(AnimationDocumentFormatError::new(
1835                            Some(line_no),
1836                            "duplicate document header",
1837                        ));
1838                    }
1839                    let parsed_version = parse_u32_field(line_no, fields[1], "version")?;
1840                    if parsed_version != ANIMATION_DOCUMENT_VERSION {
1841                        return Err(AnimationDocumentFormatError::new(
1842                            Some(line_no),
1843                            format!(
1844                                "unsupported document version {parsed_version}; expected {ANIMATION_DOCUMENT_VERSION}"
1845                            ),
1846                        ));
1847                    }
1848                    version = Some(parsed_version);
1849                }
1850                "name" => {
1851                    ensure_document_header(line_no, version)?;
1852                    expect_field_count(line_no, &fields, 2)?;
1853                    ensure_no_open_track_or_clip(line_no, &current_track, &current_clip)?;
1854                    name = Some(unescape_document_field(fields[1], line_no)?);
1855                }
1856                "duration" => {
1857                    ensure_document_header(line_no, version)?;
1858                    expect_field_count(line_no, &fields, 2)?;
1859                    ensure_no_open_track_or_clip(line_no, &current_track, &current_clip)?;
1860                    duration = Some(parse_f64_field(line_no, fields[1], "duration")?);
1861                }
1862                "clip" => {
1863                    ensure_document_header(line_no, version)?;
1864                    expect_field_count(line_no, &fields, 5)?;
1865                    if current_clip.is_some() {
1866                        return Err(AnimationDocumentFormatError::new(
1867                            Some(line_no),
1868                            "nested clips are not allowed",
1869                        ));
1870                    }
1871                    let id = unescape_document_field(fields[1], line_no)?;
1872                    let start_time = parse_f64_field(line_no, fields[2], "clip start time")?;
1873                    let clip_duration = parse_f64_field(line_no, fields[3], "clip duration")?;
1874                    let enabled = parse_bool_field(line_no, fields[4], "clip enabled")?;
1875                    let mut clip = Clip::new(id, start_time, clip_duration);
1876                    clip.enabled = enabled;
1877                    current_clip = Some(clip);
1878                }
1879                "track" => {
1880                    ensure_document_header(line_no, version)?;
1881                    expect_field_count(line_no, &fields, 4)?;
1882                    if current_clip.is_none() {
1883                        return Err(AnimationDocumentFormatError::new(
1884                            Some(line_no),
1885                            "track must appear inside a clip",
1886                        ));
1887                    }
1888                    if current_track.is_some() {
1889                        return Err(AnimationDocumentFormatError::new(
1890                            Some(line_no),
1891                            "nested tracks are not allowed",
1892                        ));
1893                    }
1894                    let target =
1895                        AnimationTargetId::new(unescape_document_field(fields[1], line_no)?);
1896                    let property_path = unescape_document_field(fields[2], line_no)?;
1897                    let enabled = parse_bool_field(line_no, fields[3], "track enabled")?;
1898                    let mut track = Track::new(AnimationBinding::new(
1899                        target,
1900                        animation_property_from_path(property_path),
1901                    ));
1902                    track.enabled = enabled;
1903                    current_track = Some(track);
1904                }
1905                "key" => {
1906                    ensure_document_header(line_no, version)?;
1907                    expect_field_count(line_no, &fields, 4)?;
1908                    let Some(track) = &mut current_track else {
1909                        return Err(AnimationDocumentFormatError::new(
1910                            Some(line_no),
1911                            "keyframe must appear inside a track",
1912                        ));
1913                    };
1914                    let time = parse_f64_field(line_no, fields[1], "keyframe time")?;
1915                    let easing = parse_easing(line_no, fields[2])?;
1916                    let value = parse_animation_value(line_no, fields[3])?;
1917                    track.push_keyframe(Keyframe::new(time, value).with_easing(easing));
1918                }
1919                "endtrack" => {
1920                    ensure_document_header(line_no, version)?;
1921                    expect_field_count(line_no, &fields, 1)?;
1922                    let Some(track) = current_track.take() else {
1923                        return Err(AnimationDocumentFormatError::new(
1924                            Some(line_no),
1925                            "endtrack without an open track",
1926                        ));
1927                    };
1928                    let Some(clip) = &mut current_clip else {
1929                        return Err(AnimationDocumentFormatError::new(
1930                            Some(line_no),
1931                            "endtrack without an open clip",
1932                        ));
1933                    };
1934                    clip.push_track(track);
1935                }
1936                "endclip" => {
1937                    ensure_document_header(line_no, version)?;
1938                    expect_field_count(line_no, &fields, 1)?;
1939                    if current_track.is_some() {
1940                        return Err(AnimationDocumentFormatError::new(
1941                            Some(line_no),
1942                            "endclip reached before endtrack",
1943                        ));
1944                    }
1945                    let Some(clip) = current_clip.take() else {
1946                        return Err(AnimationDocumentFormatError::new(
1947                            Some(line_no),
1948                            "endclip without an open clip",
1949                        ));
1950                    };
1951                    clips.push(clip);
1952                }
1953                other => {
1954                    return Err(AnimationDocumentFormatError::new(
1955                        Some(line_no),
1956                        format!("unknown directive {other:?}"),
1957                    ));
1958                }
1959            }
1960        }
1961
1962        if version.is_none() {
1963            return Err(AnimationDocumentFormatError::new(
1964                None,
1965                "missing document header",
1966            ));
1967        }
1968        if current_track.is_some() {
1969            return Err(AnimationDocumentFormatError::new(None, "unclosed track"));
1970        }
1971        if current_clip.is_some() {
1972            return Err(AnimationDocumentFormatError::new(None, "unclosed clip"));
1973        }
1974
1975        Ok(AnimationDocument {
1976            version: ANIMATION_DOCUMENT_VERSION,
1977            name: name
1978                .ok_or_else(|| AnimationDocumentFormatError::new(None, "missing document name"))?,
1979            timeline: Timeline {
1980                duration: duration.ok_or_else(|| {
1981                    AnimationDocumentFormatError::new(None, "missing timeline duration")
1982                })?,
1983                clips,
1984            },
1985        })
1986    }
1987}
1988
1989fn format_bool(value: bool) -> &'static str {
1990    if value { "true" } else { "false" }
1991}
1992
1993fn format_f64(value: f64) -> String {
1994    value.to_string()
1995}
1996
1997fn format_f32(value: f32) -> String {
1998    value.to_string()
1999}
2000
2001fn escape_document_field(value: &str) -> String {
2002    let mut escaped = String::new();
2003    for ch in value.chars() {
2004        match ch {
2005            '\\' => escaped.push_str("\\\\"),
2006            '\n' => escaped.push_str("\\n"),
2007            '\r' => escaped.push_str("\\r"),
2008            '\t' => escaped.push_str("\\t"),
2009            _ => escaped.push(ch),
2010        }
2011    }
2012    escaped
2013}
2014
2015fn unescape_document_field(
2016    value: &str,
2017    line_no: usize,
2018) -> Result<String, AnimationDocumentFormatError> {
2019    let mut unescaped = String::new();
2020    let mut chars = value.chars();
2021    while let Some(ch) = chars.next() {
2022        if ch != '\\' {
2023            unescaped.push(ch);
2024            continue;
2025        }
2026
2027        match chars.next() {
2028            Some('\\') => unescaped.push('\\'),
2029            Some('n') => unescaped.push('\n'),
2030            Some('r') => unescaped.push('\r'),
2031            Some('t') => unescaped.push('\t'),
2032            Some(other) => {
2033                return Err(AnimationDocumentFormatError::new(
2034                    Some(line_no),
2035                    format!("unsupported escape sequence \\{other}"),
2036                ));
2037            }
2038            None => {
2039                return Err(AnimationDocumentFormatError::new(
2040                    Some(line_no),
2041                    "unterminated escape sequence",
2042                ));
2043            }
2044        }
2045    }
2046    Ok(unescaped)
2047}
2048
2049fn expect_field_count(
2050    line_no: usize,
2051    fields: &[&str],
2052    expected: usize,
2053) -> Result<(), AnimationDocumentFormatError> {
2054    if fields.len() == expected {
2055        return Ok(());
2056    }
2057
2058    Err(AnimationDocumentFormatError::new(
2059        Some(line_no),
2060        format!("expected {expected} fields, found {}", fields.len()),
2061    ))
2062}
2063
2064fn ensure_document_header(
2065    line_no: usize,
2066    version: Option<u32>,
2067) -> Result<(), AnimationDocumentFormatError> {
2068    if version.is_some() {
2069        return Ok(());
2070    }
2071
2072    Err(AnimationDocumentFormatError::new(
2073        Some(line_no),
2074        "document header must be the first directive",
2075    ))
2076}
2077
2078fn ensure_no_open_track_or_clip(
2079    line_no: usize,
2080    track: &Option<Track>,
2081    clip: &Option<Clip>,
2082) -> Result<(), AnimationDocumentFormatError> {
2083    if track.is_none() && clip.is_none() {
2084        return Ok(());
2085    }
2086
2087    Err(AnimationDocumentFormatError::new(
2088        Some(line_no),
2089        "document metadata must appear before clips",
2090    ))
2091}
2092
2093fn parse_u32_field(
2094    line_no: usize,
2095    value: &str,
2096    label: &str,
2097) -> Result<u32, AnimationDocumentFormatError> {
2098    value.parse::<u32>().map_err(|_| {
2099        AnimationDocumentFormatError::new(Some(line_no), format!("invalid {label}: {value:?}"))
2100    })
2101}
2102
2103fn parse_f64_field(
2104    line_no: usize,
2105    value: &str,
2106    label: &str,
2107) -> Result<f64, AnimationDocumentFormatError> {
2108    let parsed = value.parse::<f64>().map_err(|_| {
2109        AnimationDocumentFormatError::new(Some(line_no), format!("invalid {label}: {value:?}"))
2110    })?;
2111    if parsed.is_finite() {
2112        Ok(parsed)
2113    } else {
2114        Err(AnimationDocumentFormatError::new(
2115            Some(line_no),
2116            format!("{label} must be finite"),
2117        ))
2118    }
2119}
2120
2121fn parse_f32_field(
2122    line_no: usize,
2123    value: &str,
2124    label: &str,
2125) -> Result<f32, AnimationDocumentFormatError> {
2126    let parsed = value.parse::<f32>().map_err(|_| {
2127        AnimationDocumentFormatError::new(Some(line_no), format!("invalid {label}: {value:?}"))
2128    })?;
2129    if parsed.is_finite() {
2130        Ok(parsed)
2131    } else {
2132        Err(AnimationDocumentFormatError::new(
2133            Some(line_no),
2134            format!("{label} must be finite"),
2135        ))
2136    }
2137}
2138
2139fn parse_bool_field(
2140    line_no: usize,
2141    value: &str,
2142    label: &str,
2143) -> Result<bool, AnimationDocumentFormatError> {
2144    match value {
2145        "true" => Ok(true),
2146        "false" => Ok(false),
2147        _ => Err(AnimationDocumentFormatError::new(
2148            Some(line_no),
2149            format!("{label} must be true or false"),
2150        )),
2151    }
2152}
2153
2154fn format_easing(easing: Easing) -> String {
2155    match easing {
2156        Easing::Linear => "linear".to_string(),
2157        Easing::EaseIn => "ease-in".to_string(),
2158        Easing::EaseOut => "ease-out".to_string(),
2159        Easing::EaseInOut => "ease-in-out".to_string(),
2160        Easing::CubicBezier { x1, y1, x2, y2 } => format!(
2161            "cubic-bezier:{},{},{},{}",
2162            format_f32(x1),
2163            format_f32(y1),
2164            format_f32(x2),
2165            format_f32(y2)
2166        ),
2167    }
2168}
2169
2170fn parse_easing(line_no: usize, value: &str) -> Result<Easing, AnimationDocumentFormatError> {
2171    match value {
2172        "linear" => Ok(Easing::Linear),
2173        "ease-in" => Ok(Easing::EaseIn),
2174        "ease-out" => Ok(Easing::EaseOut),
2175        "ease-in-out" => Ok(Easing::EaseInOut),
2176        _ => {
2177            let Some(params) = value.strip_prefix("cubic-bezier:") else {
2178                return Err(AnimationDocumentFormatError::new(
2179                    Some(line_no),
2180                    format!("unknown easing {value:?}"),
2181                ));
2182            };
2183            let values = parse_f32_list(line_no, params, "cubic-bezier")?;
2184            if values.len() != 4 {
2185                return Err(AnimationDocumentFormatError::new(
2186                    Some(line_no),
2187                    "cubic-bezier easing requires four values",
2188                ));
2189            }
2190            Ok(Easing::CubicBezier {
2191                x1: values[0],
2192                y1: values[1],
2193                x2: values[2],
2194                y2: values[3],
2195            })
2196        }
2197    }
2198}
2199
2200fn format_animation_value(value: AnimationValue) -> String {
2201    match value {
2202        AnimationValue::Scalar(value) => format!("scalar:{}", format_f32(value)),
2203        AnimationValue::Point(value) => {
2204            format!("point:{},{}", format_f32(value.x), format_f32(value.y))
2205        }
2206        AnimationValue::Vector(value) => {
2207            format!("vector:{},{}", format_f32(value.x), format_f32(value.y))
2208        }
2209        AnimationValue::Size(value) => {
2210            format!(
2211                "size:{},{}",
2212                format_f32(value.width),
2213                format_f32(value.height)
2214            )
2215        }
2216        AnimationValue::Rect(value) => {
2217            format!(
2218                "rect:{},{},{},{}",
2219                format_f32(value.x()),
2220                format_f32(value.y()),
2221                format_f32(value.width()),
2222                format_f32(value.height())
2223            )
2224        }
2225        AnimationValue::Color(value) => {
2226            format!(
2227                "color:{},{},{},{},{}",
2228                format_color_space(value.space),
2229                format_f32(value.red),
2230                format_f32(value.green),
2231                format_f32(value.blue),
2232                format_f32(value.alpha)
2233            )
2234        }
2235        AnimationValue::Transform(value) => {
2236            format!(
2237                "transform:{},{},{},{},{},{}",
2238                format_f32(value.xx),
2239                format_f32(value.yx),
2240                format_f32(value.xy),
2241                format_f32(value.yy),
2242                format_f32(value.dx),
2243                format_f32(value.dy)
2244            )
2245        }
2246    }
2247}
2248
2249fn parse_animation_value(
2250    line_no: usize,
2251    value: &str,
2252) -> Result<AnimationValue, AnimationDocumentFormatError> {
2253    let Some((kind, payload)) = value.split_once(':') else {
2254        return Err(AnimationDocumentFormatError::new(
2255            Some(line_no),
2256            "animation value must include a kind prefix",
2257        ));
2258    };
2259
2260    match kind {
2261        "scalar" => Ok(AnimationValue::Scalar(parse_f32_field(
2262            line_no,
2263            payload,
2264            "scalar value",
2265        )?)),
2266        "point" => {
2267            let values = parse_fixed_f32_list(line_no, payload, "point", 2)?;
2268            Ok(AnimationValue::Point(Point::new(values[0], values[1])))
2269        }
2270        "vector" => {
2271            let values = parse_fixed_f32_list(line_no, payload, "vector", 2)?;
2272            Ok(AnimationValue::Vector(Vector::new(values[0], values[1])))
2273        }
2274        "size" => {
2275            let values = parse_fixed_f32_list(line_no, payload, "size", 2)?;
2276            Ok(AnimationValue::Size(Size::new(values[0], values[1])))
2277        }
2278        "rect" => {
2279            let values = parse_fixed_f32_list(line_no, payload, "rect", 4)?;
2280            Ok(AnimationValue::Rect(Rect::new(
2281                values[0], values[1], values[2], values[3],
2282            )))
2283        }
2284        "color" => {
2285            let parts = payload.split(',').collect::<Vec<_>>();
2286            if parts.len() != 5 {
2287                return Err(AnimationDocumentFormatError::new(
2288                    Some(line_no),
2289                    "color value requires color space plus four channels",
2290                ));
2291            }
2292            Ok(AnimationValue::Color(Color::new(
2293                parse_color_space(line_no, parts[0])?,
2294                parse_f32_field(line_no, parts[1], "red channel")?,
2295                parse_f32_field(line_no, parts[2], "green channel")?,
2296                parse_f32_field(line_no, parts[3], "blue channel")?,
2297                parse_f32_field(line_no, parts[4], "alpha channel")?,
2298            )))
2299        }
2300        "transform" => {
2301            let values = parse_fixed_f32_list(line_no, payload, "transform", 6)?;
2302            Ok(AnimationValue::Transform(Transform::new(
2303                values[0], values[1], values[2], values[3], values[4], values[5],
2304            )))
2305        }
2306        _ => Err(AnimationDocumentFormatError::new(
2307            Some(line_no),
2308            format!("unknown animation value kind {kind:?}"),
2309        )),
2310    }
2311}
2312
2313fn parse_f32_list(
2314    line_no: usize,
2315    value: &str,
2316    label: &str,
2317) -> Result<Vec<f32>, AnimationDocumentFormatError> {
2318    value
2319        .split(',')
2320        .map(|field| parse_f32_field(line_no, field, label))
2321        .collect()
2322}
2323
2324fn parse_fixed_f32_list(
2325    line_no: usize,
2326    value: &str,
2327    label: &str,
2328    expected: usize,
2329) -> Result<Vec<f32>, AnimationDocumentFormatError> {
2330    let values = parse_f32_list(line_no, value, label)?;
2331    if values.len() == expected {
2332        return Ok(values);
2333    }
2334
2335    Err(AnimationDocumentFormatError::new(
2336        Some(line_no),
2337        format!("{label} value requires {expected} numbers"),
2338    ))
2339}
2340
2341fn format_color_space(color_space: ColorSpace) -> &'static str {
2342    match color_space {
2343        ColorSpace::Srgb => "srgb",
2344        ColorSpace::LinearSrgb => "linear-srgb",
2345        ColorSpace::DisplayP3 => "display-p3",
2346        ColorSpace::LinearDisplayP3 => "linear-display-p3",
2347    }
2348}
2349
2350fn parse_color_space(
2351    line_no: usize,
2352    value: &str,
2353) -> Result<ColorSpace, AnimationDocumentFormatError> {
2354    match value {
2355        "srgb" => Ok(ColorSpace::Srgb),
2356        "linear-srgb" => Ok(ColorSpace::LinearSrgb),
2357        "display-p3" => Ok(ColorSpace::DisplayP3),
2358        "linear-display-p3" => Ok(ColorSpace::LinearDisplayP3),
2359        _ => Err(AnimationDocumentFormatError::new(
2360            Some(line_no),
2361            format!("unknown color space {value:?}"),
2362        )),
2363    }
2364}
2365
2366fn animation_property_from_path(path: String) -> AnimationProperty {
2367    match path.as_str() {
2368        "layer.opacity" => AnimationProperty::LayerOpacity,
2369        "layer.translation" => AnimationProperty::LayerTranslation,
2370        "fill.color" => AnimationProperty::FillColor,
2371        "bounds" => AnimationProperty::Bounds,
2372        _ => AnimationProperty::Custom(AnimationPropertyPath::new(path)),
2373    }
2374}
2375
2376fn sample_cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, t: f32) -> f32 {
2377    if t <= 0.0 {
2378        return 0.0;
2379    }
2380    if t >= 1.0 {
2381        return 1.0;
2382    }
2383
2384    let sample_curve = |a: f32, b: f32, c: f32, u: f32| {
2385        let inv = 1.0 - u;
2386        (3.0 * inv * inv * u * a) + (3.0 * inv * u * u * b) + (u * u * u * c)
2387    };
2388
2389    let mut low = 0.0;
2390    let mut high = 1.0;
2391    let mut u = t;
2392    for _ in 0..10 {
2393        u = (low + high) * 0.5;
2394        let x = sample_curve(x1, x2, 1.0, u);
2395        if (x - t).abs() < 1e-5 {
2396            break;
2397        }
2398        if x < t {
2399            low = u;
2400        } else {
2401            high = u;
2402        }
2403    }
2404
2405    sample_curve(y1, y2, 1.0, u)
2406}
2407
2408#[cfg(test)]
2409mod tests {
2410    use super::{
2411        AnimatedValue, AnimationBinding, AnimationDocument, AnimationEditorCommand,
2412        AnimationEditorState, AnimationPlayer, AnimationProperty, AnimationPropertyPath,
2413        AnimationTargetId, AnimationValue, Blink, Clip, Easing, Interpolate, Keyframe,
2414        KeyframeSelection, LoopMode, PlaybackState, Pulse, SampleBuffer, SpringF32, Timeline,
2415        Track, Transition,
2416    };
2417    use sui_core::{Color, ColorSpace, Rect, Transform, Vector};
2418
2419    fn opacity_binding() -> AnimationBinding {
2420        AnimationBinding::new(
2421            AnimationTargetId::new("hero-card"),
2422            AnimationProperty::LayerOpacity,
2423        )
2424    }
2425
2426    #[test]
2427    fn interpolate_supports_common_sui_values() {
2428        assert!((f32::interpolate(2.0, 6.0, 0.25) - 3.0).abs() < 1e-6);
2429        assert_eq!(
2430            Vector::interpolate(Vector::new(0.0, 4.0), Vector::new(8.0, 12.0), 0.5),
2431            Vector::new(4.0, 8.0)
2432        );
2433        assert_eq!(
2434            Rect::interpolate(
2435                Rect::new(0.0, 2.0, 10.0, 20.0),
2436                Rect::new(10.0, 12.0, 30.0, 40.0),
2437                0.5
2438            ),
2439            Rect::new(5.0, 7.0, 20.0, 30.0)
2440        );
2441        let interpolated = Color::interpolate(
2442            Color::rgba(0.2, 0.4, 0.6, 1.0),
2443            Color::rgba(0.6, 0.8, 1.0, 0.0),
2444            0.5,
2445        );
2446        let expected = Color::rgba(0.4, 0.6, 0.8, 0.5);
2447        assert_eq!(interpolated.space, expected.space);
2448        assert!((interpolated.red - expected.red).abs() < 1e-6);
2449        assert!((interpolated.green - expected.green).abs() < 1e-6);
2450        assert!((interpolated.blue - expected.blue).abs() < 1e-6);
2451        assert!((interpolated.alpha - expected.alpha).abs() < 1e-6);
2452    }
2453
2454    #[test]
2455    fn transition_samples_ease_in_out_curve() {
2456        let transition = Transition::new(0.0_f32, 1.0, 10.0, 2.0, Easing::EaseInOut);
2457
2458        assert_eq!(transition.sample(10.0), 0.0);
2459        assert!(transition.sample(11.0) > 0.45 && transition.sample(11.0) < 0.55);
2460        assert_eq!(transition.sample(12.0), 1.0);
2461        assert!(transition.is_complete(12.0));
2462    }
2463
2464    #[test]
2465    fn cubic_bezier_easing_has_stable_endpoints() {
2466        let easing = Easing::CubicBezier {
2467            x1: 0.4,
2468            y1: 0.0,
2469            x2: 0.2,
2470            y2: 1.0,
2471        };
2472
2473        assert_eq!(easing.sample(0.0), 0.0);
2474        assert_eq!(easing.sample(1.0), 1.0);
2475        let midpoint = easing.sample(0.5);
2476        assert!(midpoint > 0.0 && midpoint < 1.0);
2477    }
2478
2479    #[test]
2480    fn track_samples_keyframes_without_requiring_sorted_input() {
2481        let track = Track::new(opacity_binding()).with_keyframes([
2482            Keyframe::new(1.0, 1.0_f32),
2483            Keyframe::new(0.0, 0.0_f32).with_easing(Easing::Linear),
2484        ]);
2485
2486        assert_eq!(track.sample(-1.0), Some(0.0));
2487        assert_eq!(track.sample(0.5), Some(0.5));
2488        assert_eq!(track.sample(2.0), Some(1.0));
2489    }
2490
2491    #[test]
2492    fn timeline_samples_clip_tracks_in_global_time() {
2493        let opacity_track = Track::new(opacity_binding()).with_keyframes([
2494            Keyframe::new(0.0, AnimationValue::Scalar(0.25)),
2495            Keyframe::new(2.0, AnimationValue::Scalar(1.0)),
2496        ]);
2497        let timeline =
2498            Timeline::new(4.0).with_clip(Clip::new("intro", 1.0, 2.0).with_track(opacity_track));
2499
2500        assert!(timeline.sample(0.5).is_empty());
2501        let samples = timeline.sample(2.0);
2502        assert_eq!(samples.len(), 1);
2503        assert_eq!(samples[0].clip_id, "intro");
2504        let opacity = samples[0]
2505            .value
2506            .as_scalar()
2507            .expect("opacity sample should be scalar");
2508        assert!((opacity - 0.625).abs() < 1e-6);
2509    }
2510
2511    #[test]
2512    fn timeline_sample_into_reuses_output_storage() {
2513        let opacity_track = Track::new(opacity_binding()).with_keyframes([
2514            Keyframe::new(0.0, AnimationValue::Scalar(0.25)),
2515            Keyframe::new(1.0, AnimationValue::Scalar(0.75)),
2516        ]);
2517        let timeline =
2518            Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(opacity_track));
2519        let mut samples = SampleBuffer::with_capacity(8);
2520        let initial_capacity = samples.capacity();
2521
2522        {
2523            let batch = timeline.sample_into(0.5, &mut samples);
2524            assert_eq!(batch.len(), 1);
2525            assert_eq!(batch.samples()[0].clip_id, "intro");
2526            assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.5));
2527        }
2528        assert_eq!(samples.capacity(), initial_capacity);
2529
2530        {
2531            let batch = timeline.sample_into(2.0, &mut samples);
2532            assert_eq!(batch.len(), 1);
2533            assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.75));
2534        }
2535        assert_eq!(samples.capacity(), initial_capacity);
2536    }
2537
2538    #[test]
2539    fn compiled_timeline_sorts_tracks_and_omits_disabled_data() {
2540        let opacity_track = Track::new(opacity_binding()).with_keyframes([
2541            Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
2542            Keyframe::new(0.0, AnimationValue::Scalar(0.0)).with_easing(Easing::Linear),
2543        ]);
2544        let disabled_track = Track::new(AnimationBinding::new(
2545            AnimationTargetId::new("hero-card"),
2546            AnimationProperty::FillColor,
2547        ))
2548        .with_enabled(false)
2549        .with_keyframes([
2550            Keyframe::new(0.0, AnimationValue::Color(Color::rgba(1.0, 0.0, 0.0, 1.0))),
2551            Keyframe::new(1.0, AnimationValue::Color(Color::rgba(0.0, 0.0, 1.0, 1.0))),
2552        ]);
2553        let disabled_clip = Clip::new("disabled", 0.0, 1.0).with_track(
2554            Track::new(opacity_binding()).with_keyframes([
2555                Keyframe::new(0.0, AnimationValue::Scalar(0.0)),
2556                Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
2557            ]),
2558        );
2559        let mut disabled_clip = disabled_clip;
2560        disabled_clip.enabled = false;
2561        let timeline = Timeline::new(1.0)
2562            .with_clip(
2563                Clip::new("intro", 0.0, 1.0)
2564                    .with_track(opacity_track)
2565                    .with_track(disabled_track),
2566            )
2567            .with_clip(disabled_clip);
2568
2569        let compiled = timeline.compile();
2570        let mut samples = SampleBuffer::new();
2571        let batch = compiled.sample_into(0.5, &mut samples);
2572
2573        assert_eq!(compiled.clips().len(), 1);
2574        assert_eq!(compiled.sample_capacity(), 1);
2575        assert_eq!(batch.len(), 1);
2576        assert_eq!(batch.samples()[0].clip_id, "intro");
2577        assert_eq!(
2578            batch.samples()[0].binding.property,
2579            AnimationProperty::LayerOpacity
2580        );
2581        assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.5));
2582    }
2583
2584    #[test]
2585    fn animation_player_ticks_shared_compiled_timeline_into_sample_buffer() {
2586        let timeline = Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(
2587            Track::new(opacity_binding()).with_keyframes([
2588                Keyframe::new(0.0, AnimationValue::Scalar(0.0)).with_easing(Easing::Linear),
2589                Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
2590            ]),
2591        ));
2592        let compiled = timeline.compile_shared();
2593        let mut player = AnimationPlayer::new(compiled.clone()).repeat();
2594        let mut sibling = AnimationPlayer::new(compiled);
2595        let mut samples = SampleBuffer::with_capacity(1);
2596        player.play();
2597
2598        let tick = player.tick_into(0.5, &mut samples);
2599
2600        assert!(tick.advanced);
2601        assert!(tick.should_continue);
2602        assert_eq!(tick.playback.playhead, 0.5);
2603        assert_eq!(tick.sample_values()[0].value.as_scalar(), Some(0.5));
2604
2605        sibling.seek(0.25);
2606        let batch = sibling.sample_into(&mut samples);
2607        assert_eq!(batch.samples()[0].value.as_scalar(), Some(0.25));
2608    }
2609
2610    #[test]
2611    fn playback_state_advances_and_repeats() {
2612        let mut playback = PlaybackState {
2613            loop_mode: LoopMode::Repeat,
2614            ..PlaybackState::default()
2615        };
2616        playback.play();
2617
2618        assert!(playback.tick(1.25, 1.0));
2619        assert!((playback.playhead - 0.25).abs() < 1e-6);
2620        assert!(playback.playing);
2621    }
2622
2623    #[test]
2624    fn blink_is_deterministic_for_same_time_inputs() {
2625        let blink = Blink::new(0.8).with_duty_cycle(0.25).with_phase(0.1);
2626
2627        assert_eq!(blink.is_on(1.25), blink.is_on(1.25));
2628        assert!(blink.is_on(0.0));
2629        assert!(!blink.is_on(0.35));
2630    }
2631
2632    #[test]
2633    fn pulse_samples_repeatable_range() {
2634        let pulse = Pulse::new(1.0, 0.2, 1.0);
2635        let a = pulse.sample(0.25);
2636        let b = pulse.sample(0.25);
2637        assert_eq!(a, b);
2638        assert!((0.2..=1.0).contains(&a));
2639    }
2640
2641    #[test]
2642    fn spring_helpers_converge_toward_target_values() {
2643        let mut spring = SpringF32::new(0.0).with_config(140.0, 22.0);
2644        let mut value = 0.0;
2645        for _ in 0..120 {
2646            value = spring.step(1.0, 1.0 / 120.0);
2647        }
2648
2649        assert!(value > 0.95);
2650        assert!((value - 1.0).abs() < 0.05);
2651    }
2652
2653    #[test]
2654    fn animated_value_reaches_target_and_reports_completion() {
2655        let mut animated = AnimatedValue::new(0.0_f32)
2656            .with_duration(0.2)
2657            .with_easing(Easing::Linear);
2658        animated.set_target(1.0);
2659        assert!(animated.is_animating());
2660
2661        assert!(animated.tick(0.1));
2662        assert!((animated.value() - 0.5).abs() < 1e-4);
2663
2664        assert!(!animated.tick(0.1));
2665        assert_eq!(animated.value(), 1.0);
2666        assert!(!animated.is_animating());
2667        assert!(!animated.tick(0.1));
2668    }
2669
2670    #[test]
2671    fn animated_value_with_zero_duration_snaps_immediately() {
2672        let mut animated = AnimatedValue::new(2.0_f32).with_duration(0.0);
2673        animated.set_target(9.0);
2674
2675        assert!(!animated.is_animating());
2676        assert_eq!(animated.value(), 9.0);
2677        assert!(!animated.tick(1.0));
2678    }
2679
2680    #[test]
2681    fn editor_state_adds_keyframes_and_undoes_document_changes() {
2682        let track = Track::new(opacity_binding());
2683        let document = AnimationDocument::new(
2684            "Editor test",
2685            Timeline::new(2.0).with_clip(Clip::new("intro", 0.0, 2.0).with_track(track)),
2686        );
2687        let mut editor = AnimationEditorState::new(document);
2688
2689        assert!(editor.apply_command(AnimationEditorCommand::AddKeyframe {
2690            clip_index: 0,
2691            track_index: 0,
2692            keyframe: Keyframe::new(0.51, AnimationValue::Scalar(0.8)),
2693        }));
2694        assert_eq!(editor.undo_len(), 1);
2695        assert_eq!(
2696            editor.document.timeline.clips[0].tracks[0].keyframes[0].time,
2697            0.5
2698        );
2699
2700        assert!(editor.undo());
2701        assert!(
2702            editor.document.timeline.clips[0].tracks[0]
2703                .keyframes
2704                .is_empty()
2705        );
2706        assert!(editor.redo());
2707        assert_eq!(
2708            editor.document.timeline.clips[0].tracks[0].keyframes.len(),
2709            1
2710        );
2711    }
2712
2713    #[test]
2714    fn editor_selection_tracks_keyframes_without_mutating_document() {
2715        let mut editor = AnimationEditorState::default();
2716        let selection = KeyframeSelection {
2717            clip_index: 2,
2718            track_index: 1,
2719            keyframe_index: 3,
2720        };
2721
2722        assert!(editor.apply_command(AnimationEditorCommand::SelectKeyframe(selection)));
2723        assert_eq!(editor.selection.keyframes, vec![selection]);
2724        assert_eq!(editor.undo_len(), 0);
2725    }
2726
2727    #[test]
2728    fn editor_updates_keyframe_easing_with_undo() {
2729        let track = Track::new(opacity_binding()).with_keyframes([
2730            Keyframe::new(0.0, AnimationValue::Scalar(0.0)),
2731            Keyframe::new(1.0, AnimationValue::Scalar(1.0)),
2732        ]);
2733        let document = AnimationDocument::new(
2734            "Easing test",
2735            Timeline::new(1.0).with_clip(Clip::new("intro", 0.0, 1.0).with_track(track)),
2736        );
2737        let mut editor = AnimationEditorState::new(document);
2738        let selection = KeyframeSelection {
2739            clip_index: 0,
2740            track_index: 0,
2741            keyframe_index: 0,
2742        };
2743
2744        assert!(
2745            editor.apply_command(AnimationEditorCommand::UpdateKeyframeEasing {
2746                selection,
2747                easing: Easing::EaseInOut,
2748            })
2749        );
2750        assert_eq!(
2751            editor.document.timeline.clips[0].tracks[0].keyframes[0].easing,
2752            Easing::EaseInOut
2753        );
2754        assert!(editor.undo());
2755        assert_eq!(
2756            editor.document.timeline.clips[0].tracks[0].keyframes[0].easing,
2757            Easing::Linear
2758        );
2759    }
2760
2761    #[test]
2762    fn animation_document_format_round_trips_timeline_data() {
2763        let target = AnimationTargetId::new("preview card\tmain");
2764        let binding = |property| AnimationBinding::new(target.clone(), property);
2765        let mut fill_track = Track::new(binding(AnimationProperty::FillColor)).with_keyframes([
2766            Keyframe::new(
2767                0.0,
2768                AnimationValue::Color(Color::new(ColorSpace::DisplayP3, 0.1, 0.2, 0.3, 0.4)),
2769            )
2770            .with_easing(Easing::CubicBezier {
2771                x1: 0.4,
2772                y1: 0.0,
2773                x2: 0.2,
2774                y2: 1.0,
2775            }),
2776            Keyframe::new(
2777                1.0,
2778                AnimationValue::Color(Color::new(ColorSpace::LinearDisplayP3, 0.7, 0.6, 0.5, 1.0)),
2779            ),
2780        ]);
2781        fill_track.enabled = false;
2782        let mut clip = Clip::new("intro\nclip", 0.25, 2.0)
2783            .with_track(
2784                Track::new(binding(AnimationProperty::LayerTranslation)).with_keyframes([
2785                    Keyframe::new(0.0, AnimationValue::Vector(Vector::new(-12.0, 4.5)))
2786                        .with_easing(Easing::EaseInOut),
2787                    Keyframe::new(1.0, AnimationValue::Vector(Vector::new(22.0, -8.0))),
2788                ]),
2789            )
2790            .with_track(fill_track)
2791            .with_track(
2792                Track::new(binding(AnimationProperty::Custom(
2793                    AnimationPropertyPath::new("paint.radius"),
2794                )))
2795                .with_keyframes([
2796                    Keyframe::new(0.0, AnimationValue::Scalar(6.0)).with_easing(Easing::EaseOut),
2797                    Keyframe::new(1.0, AnimationValue::Scalar(18.0)),
2798                ]),
2799            )
2800            .with_track(
2801                Track::new(binding(AnimationProperty::Custom(
2802                    AnimationPropertyPath::new("local.transform"),
2803                )))
2804                .with_keyframes([Keyframe::new(
2805                    0.5,
2806                    AnimationValue::Transform(Transform::translation(8.0, 9.0)),
2807                )]),
2808            );
2809        clip.enabled = true;
2810        let document = AnimationDocument::new(
2811            "Demo\tAnimation\nDocument",
2812            Timeline::new(3.5).with_clip(clip),
2813        );
2814
2815        let serialized = document.to_document_format();
2816        assert!(serialized.starts_with("sui-animation-document\t1\n"));
2817        assert!(serialized.contains("paint.radius"));
2818
2819        let parsed = AnimationDocument::from_document_format(&serialized)
2820            .expect("serialized document should parse");
2821        assert_eq!(parsed, document);
2822        assert_eq!(parsed.to_document_format(), serialized);
2823    }
2824
2825    #[test]
2826    fn animation_document_format_rejects_unsupported_versions() {
2827        let err = AnimationDocument::from_document_format(
2828            "sui-animation-document\t99\nname\tBad\nduration\t1\n",
2829        )
2830        .expect_err("unsupported version should fail");
2831
2832        assert_eq!(err.line, Some(1));
2833        assert!(err.message.contains("unsupported document version"));
2834    }
2835
2836    #[test]
2837    fn animation_document_format_rejects_unclosed_tracks() {
2838        let err = AnimationDocument::from_document_format(
2839            "sui-animation-document\t1\nname\tBad\nduration\t1\nclip\tintro\t0\t1\ttrue\ntrack\ttarget\tlayer.opacity\ttrue\n",
2840        )
2841        .expect_err("unclosed track should fail");
2842
2843        assert!(err.message.contains("unclosed track"));
2844    }
2845}