cranpose-animation 0.1.126

Animation system for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
//! Animation system for Cranpose
//!
//! Provides time-based animations with easing curves and spring physics.
//!
//! Note: This module uses camelCase for method names (animateTo, snapTo) to maintain
//! 1:1 API parity with Jetpack Compose.

#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]

use std::{
    cell::{Cell, RefCell},
    marker::PhantomData,
    rc::{Rc, Weak},
};

use cranpose_core::{
    DisposableEffectResult, Owned, OwnedMutableState, RuntimeHandle, SideEffect, State,
    internal::FrameCallbackRegistration, with_current_composer,
};

/// Trait for types that can be linearly interpolated.
pub trait Lerp {
    fn lerp(&self, target: &Self, fraction: f32) -> Self;
}

impl Lerp for f32 {
    fn lerp(&self, target: &Self, fraction: f32) -> Self {
        self + (target - self) * fraction
    }
}

impl Lerp for f64 {
    fn lerp(&self, target: &Self, fraction: f32) -> Self {
        self + (target - self) * fraction as f64
    }
}

/// Values springs can animate: fixed-dimension float vectors (at most
/// [`SPRING_MAX_DIMENSIONS`]), mirroring Compose's `AnimationVector1D..4D`.
///
/// The spring integrates each dimension independently **in value space** —
/// velocity is expressed in value units per second — so retargeting an
/// animation mid-flight keeps the physical velocity (no hitch), and gestures
/// can hand their release velocity to [`Animatable::animate_to_with_velocity`].
pub trait SpringScalar: Lerp + Clone + PartialEq {
    /// Number of animated dimensions (1..=4).
    const DIMENSIONS: usize;

    /// Reads dimension `index` (`index < Self::DIMENSIONS`).
    fn dimension(&self, index: usize) -> f32;

    /// Rebuilds a value from per-dimension floats (indices beyond
    /// [`Self::DIMENSIONS`] are ignored).
    fn from_dimensions(dimensions: [f32; SPRING_MAX_DIMENSIONS]) -> Self;
}

/// Upper bound on [`SpringScalar::DIMENSIONS`].
pub const SPRING_MAX_DIMENSIONS: usize = 4;

/// Advances one damped-harmonic-oscillator dimension by `dt` seconds using the
/// closed-form solution for unit mass (`ω = √stiffness`, damping `c = 2ζω`).
/// Returns the new `(value, velocity)`; exact for any `dt`, so springs stay
/// correct across dropped frames and long pauses.
pub fn advance_spring(
    value: f32,
    velocity: f32,
    target: f32,
    damping_ratio: f32,
    stiffness: f32,
    dt: f32,
) -> (f32, f32) {
    let omega = stiffness.max(f32::EPSILON).sqrt();
    let zeta = damping_ratio.max(0.0);
    let displacement = value - target;

    if (zeta - 1.0).abs() < 1e-4 {
        let c1 = displacement;
        let c2 = velocity + omega * displacement;
        let decay = (-omega * dt).exp();
        let next_displacement = (c1 + c2 * dt) * decay;
        let next_velocity = (c2 - omega * (c1 + c2 * dt)) * decay;
        (target + next_displacement, next_velocity)
    } else if zeta < 1.0 {
        let omega_d = omega * (1.0 - zeta * zeta).sqrt();
        let decay = (-zeta * omega * dt).exp();
        let (sin, cos) = (omega_d * dt).sin_cos();
        let a = displacement;
        let b = (velocity + zeta * omega * displacement) / omega_d;
        let next_displacement = decay * (a * cos + b * sin);
        let next_velocity = decay
            * ((b * omega_d - a * zeta * omega) * cos - (a * omega_d + b * zeta * omega) * sin);
        (target + next_displacement, next_velocity)
    } else {
        let root = (zeta * zeta - 1.0).sqrt();
        let r1 = -omega * (zeta - root);
        let r2 = -omega * (zeta + root);
        let c2 = (velocity - r1 * displacement) / (r2 - r1);
        let c1 = displacement - c2;
        let e1 = (r1 * dt).exp();
        let e2 = (r2 * dt).exp();
        (target + c1 * e1 + c2 * e2, c1 * r1 * e1 + c2 * r2 * e2)
    }
}

impl SpringScalar for f32 {
    const DIMENSIONS: usize = 1;

    fn dimension(&self, _index: usize) -> f32 {
        *self
    }

    fn from_dimensions(dimensions: [f32; SPRING_MAX_DIMENSIONS]) -> Self {
        dimensions[0]
    }
}

impl SpringScalar for f64 {
    const DIMENSIONS: usize = 1;

    fn dimension(&self, _index: usize) -> f32 {
        *self as f32
    }

    fn from_dimensions(dimensions: [f32; SPRING_MAX_DIMENSIONS]) -> Self {
        f64::from(dimensions[0])
    }
}

/// Easing functions for animations matching Jetpack Compose.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Easing {
    /// Linear interpolation (no easing).
    /// Jetpack Compose: LinearEasing
    LinearEasing,
    /// Ease in using cubic curve.
    /// Jetpack Compose: EaseIn (not a standard constant, but supported)
    EaseIn,
    /// Ease out using cubic curve.
    /// Jetpack Compose: EaseOut (not a standard constant, but supported)
    EaseOut,
    /// Ease in and out using cubic curve.
    /// Jetpack Compose: EaseInOut (not a standard constant, but supported)
    EaseInOut,
    /// Fast out, slow in (material design standard).
    /// Jetpack Compose: FastOutSlowInEasing
    FastOutSlowInEasing,
    /// Linear out, slow in (material design).
    /// Jetpack Compose: LinearOutSlowInEasing
    LinearOutSlowInEasing,
    /// Fast out, linear in (material design).
    /// Jetpack Compose: FastOutLinearEasing
    FastOutLinearEasing,
    /// Holds each of `step_count` evenly spaced values for one discrete step.
    Steps(u32),
}

impl Easing {
    /// Apply the easing function to a linear fraction [0, 1].
    pub fn transform(&self, fraction: f32) -> f32 {
        match self {
            Easing::LinearEasing => fraction,
            Easing::EaseIn => cubic_bezier(0.42, 0.0, 1.0, 1.0, fraction),
            Easing::EaseOut => cubic_bezier(0.0, 0.0, 0.58, 1.0, fraction),
            Easing::EaseInOut => cubic_bezier(0.42, 0.0, 0.58, 1.0, fraction),
            Easing::FastOutSlowInEasing => cubic_bezier(0.4, 0.0, 0.2, 1.0, fraction),
            Easing::LinearOutSlowInEasing => cubic_bezier(0.0, 0.0, 0.2, 1.0, fraction),
            Easing::FastOutLinearEasing => cubic_bezier(0.4, 0.0, 1.0, 1.0, fraction),
            Easing::Steps(step_count) => {
                if fraction <= 0.0 || fraction >= 1.0 {
                    fraction
                } else {
                    let step_count = (*step_count).max(1) as f32;
                    (fraction * step_count).floor() / step_count
                }
            }
        }
    }
}

/// Cubic bezier curve approximation for easing.
fn cubic_bezier(x1: f32, y1: f32, x2: f32, y2: f32, fraction: f32) -> f32 {
    if fraction <= 0.0 {
        return 0.0;
    }
    if fraction >= 1.0 {
        return 1.0;
    }

    let cx = 3.0 * x1;
    let bx = 3.0 * (x2 - x1) - cx;
    let ax = 1.0 - cx - bx;

    let cy = 3.0 * y1;
    let by = 3.0 * (y2 - y1) - cy;
    let ay = 1.0 - cy - by;

    fn sample_curve(a: f32, b: f32, c: f32, t: f32) -> f32 {
        ((a * t + b) * t + c) * t
    }

    fn sample_derivative(a: f32, b: f32, c: f32, t: f32) -> f32 {
        (3.0 * a * t + 2.0 * b) * t + c
    }

    let mut t = fraction;
    let mut newton_success = false;
    for _ in 0..8 {
        let x = sample_curve(ax, bx, cx, t) - fraction;
        if x.abs() < 1e-6 {
            newton_success = true;
            break;
        }
        let dx = sample_derivative(ax, bx, cx, t);
        if dx.abs() < 1e-6 {
            break;
        }
        t = (t - x / dx).clamp(0.0, 1.0);
    }

    if !newton_success {
        let mut t0 = 0.0;
        let mut t1 = 1.0;
        t = fraction;
        for _ in 0..16 {
            let x = sample_curve(ax, bx, cx, t);
            let delta = x - fraction;
            if delta.abs() < 1e-6 {
                break;
            }
            if delta > 0.0 {
                t1 = t;
            } else {
                t0 = t;
            }
            t = 0.5 * (t0 + t1);
        }
    }

    sample_curve(ay, by, cy, t)
}

/// Animation specification combining duration and easing.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AnimationSpec {
    /// Duration in milliseconds.
    pub duration_millis: u64,
    /// Easing function to apply.
    pub easing: Easing,
    /// Delay before starting animation in milliseconds.
    pub delay_millis: u64,
}

impl AnimationSpec {
    /// Create a tween animation with duration and easing.
    pub fn tween(duration_millis: u64, easing: Easing) -> Self {
        Self {
            duration_millis,
            easing,
            delay_millis: 0,
        }
    }

    /// Create a linear tween animation.
    pub fn linear(duration_millis: u64) -> Self {
        Self::tween(duration_millis, Easing::LinearEasing)
    }

    /// Creates a tween that exposes `step_count` evenly spaced values.
    ///
    /// # Panics
    ///
    /// Panics when `step_count` is zero.
    pub fn stepped(duration_millis: u64, step_count: u32) -> Self {
        assert!(step_count > 0, "step_count must be greater than zero");
        Self::tween(duration_millis, Easing::Steps(step_count))
    }

    /// Add a delay before the animation starts.
    pub fn with_delay(mut self, delay_millis: u64) -> Self {
        self.delay_millis = delay_millis;
        self
    }
}

impl Default for AnimationSpec {
    fn default() -> Self {
        Self::tween(300, Easing::FastOutSlowInEasing)
    }
}

/// Repeat mode for infinite animations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepeatMode {
    /// Restart from the beginning each cycle.
    Restart,
    /// Reverse direction every other cycle.
    Reverse,
}

/// Start offset type for infinite animations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StartOffsetType {
    /// Delay the start by the specified offset.
    Delay,
    /// Fast forward the start by the specified offset.
    FastForward,
}

/// Start offset configuration for infinite animations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StartOffset {
    /// Offset in milliseconds.
    pub offset_millis: i64,
    /// Offset behavior (delay or fast-forward).
    pub offset_type: StartOffsetType,
}

impl Default for StartOffset {
    fn default() -> Self {
        Self {
            offset_millis: 0,
            offset_type: StartOffsetType::Delay,
        }
    }
}

/// Infinite repeatable animation spec built from a duration-based animation.
#[derive(Debug, Clone, PartialEq)]
pub struct InfiniteRepeatableSpec<T> {
    /// Base animation used for each iteration.
    pub animation: AnimationSpec,
    /// Repeat mode (restart or reverse).
    pub repeat_mode: RepeatMode,
    /// Start offset applied before the first iteration.
    pub initial_start_offset: StartOffset,
    _marker: PhantomData<fn() -> T>,
}

/// Creates an infinite repeatable animation spec.
pub fn infiniteRepeatable<T>(
    animation: AnimationSpec,
    repeat_mode: RepeatMode,
    initial_start_offset: StartOffset,
) -> InfiniteRepeatableSpec<T> {
    InfiniteRepeatableSpec {
        animation,
        repeat_mode,
        initial_start_offset,
        _marker: PhantomData,
    }
}

/// Spring animation configuration.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SpringSpec {
    /// Damping ratio. 1.0 = critically damped, < 1.0 = under-damped (bouncy), > 1.0 = over-damped.
    pub damping_ratio: f32,
    /// Stiffness constant. Higher values = faster animation.
    pub stiffness: f32,
    /// Velocity threshold to stop animation.
    pub velocity_threshold: f32,
    /// Position threshold to stop animation.
    pub position_threshold: f32,
    /// Delay before the spring begins advancing.
    pub delay_millis: u64,
}

impl SpringSpec {
    /// Create a spring with explicit Compose-style physics constants.
    pub fn new(damping_ratio: f32, stiffness: f32) -> Self {
        Self {
            damping_ratio,
            stiffness,
            velocity_threshold: 0.1,
            position_threshold: 0.01,
            delay_millis: 0,
        }
    }

    /// Add a delay before the spring starts integrating.
    pub fn with_delay(mut self, delay_millis: u64) -> Self {
        self.delay_millis = delay_millis;
        self
    }

    /// Create a spring with default material design values.
    pub fn default_spring() -> Self {
        Self {
            damping_ratio: 1.0,
            stiffness: 1500.0,
            velocity_threshold: 0.1,
            position_threshold: 0.01,
            delay_millis: 0,
        }
    }

    /// Create a bouncy spring.
    pub fn bouncy() -> Self {
        Self {
            damping_ratio: 0.5,
            stiffness: 1500.0,
            velocity_threshold: 0.1,
            position_threshold: 0.01,
            delay_millis: 0,
        }
    }

    /// Create a stiff spring (fast, no bounce).
    pub fn stiff() -> Self {
        Self {
            damping_ratio: 1.0,
            stiffness: 3000.0,
            velocity_threshold: 0.1,
            position_threshold: 0.01,
            delay_millis: 0,
        }
    }
}

impl Default for SpringSpec {
    fn default() -> Self {
        Self::default_spring()
    }
}

/// Compose-compatible spring constants.
pub struct Spring;

impl Spring {
    pub const DampingRatioNoBouncy: f32 = 1.0;
    pub const DampingRatioLowBouncy: f32 = 0.75;
    pub const DampingRatioMediumBouncy: f32 = 0.5;
    pub const DampingRatioHighBouncy: f32 = 0.2;

    pub const StiffnessHigh: f32 = 10_000.0;
    pub const StiffnessMedium: f32 = 1_500.0;
    pub const StiffnessMediumLow: f32 = 400.0;
    pub const StiffnessLow: f32 = 200.0;
    pub const StiffnessVeryLow: f32 = 50.0;
}

/// Compose-style spring animation spec factory.
pub fn spring(damping_ratio: f32, stiffness: f32) -> AnimationType {
    AnimationType::Spring(SpringSpec::new(damping_ratio, stiffness))
}

/// Compose-style tween animation spec factory.
pub fn tween(duration_millis: u64, easing: Easing) -> AnimationType {
    AnimationType::Tween(AnimationSpec::tween(duration_millis, easing))
}

/// Animation type specification.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AnimationType {
    /// Time-based tween animation.
    Tween(AnimationSpec),
    /// Physics-based spring animation.
    Spring(SpringSpec),
}

impl AnimationType {
    /// Add the same start delay regardless of the animation model.
    pub fn with_delay(self, delay_millis: u64) -> Self {
        match self {
            Self::Tween(spec) => Self::Tween(spec.with_delay(delay_millis)),
            Self::Spring(spec) => Self::Spring(spec.with_delay(delay_millis)),
        }
    }
}

impl Default for AnimationType {
    fn default() -> Self {
        AnimationType::Tween(AnimationSpec::default())
    }
}

trait InfiniteTransitionAnimation {
    fn on_frame(&self, play_time_nanos: u64);
    fn has_subscribers(&self) -> bool;
}

struct TransitionAnimationState<T: Lerp + Clone + PartialEq + 'static> {
    value_state: OwnedMutableState<T>,
    initial_value: RefCell<T>,
    target_value: RefCell<T>,
    spec: RefCell<InfiniteRepeatableSpec<T>>,
    start_on_next_frame: Cell<bool>,
    play_time_offset_nanos: Cell<u64>,
    subscriber_callback_installed: Cell<bool>,
    subscriber_callback: RefCell<Option<Rc<dyn Fn()>>>,
}

impl<T: Lerp + Clone + PartialEq + 'static> TransitionAnimationState<T> {
    fn new(
        initial_value: T,
        target_value: T,
        spec: InfiniteRepeatableSpec<T>,
        runtime: RuntimeHandle,
    ) -> Self {
        Self {
            value_state: OwnedMutableState::with_runtime_structural_eq(
                initial_value.clone(),
                runtime,
            ),
            initial_value: RefCell::new(initial_value),
            target_value: RefCell::new(target_value),
            spec: RefCell::new(spec),
            start_on_next_frame: Cell::new(true),
            play_time_offset_nanos: Cell::new(0),
            subscriber_callback_installed: Cell::new(false),
            subscriber_callback: RefCell::new(None),
        }
    }

    fn state(&self) -> State<T> {
        self.value_state.as_state()
    }

    fn update_values(&self, initial_value: T, target_value: T, spec: InfiniteRepeatableSpec<T>) {
        let needs_update = {
            let current_initial = self.initial_value.borrow();
            let current_target = self.target_value.borrow();
            *current_initial != initial_value
                || *current_target != target_value
                || *self.spec.borrow() != spec
        };

        if needs_update {
            *self.initial_value.borrow_mut() = initial_value.clone();
            *self.target_value.borrow_mut() = target_value;
            *self.spec.borrow_mut() = spec;
            self.start_on_next_frame.set(true);
            self.value_state.set(initial_value);
        }
    }

    fn compute_value(&self, play_time_nanos: u64) -> T {
        let offset = if self.start_on_next_frame.get() {
            self.start_on_next_frame.set(false);
            self.play_time_offset_nanos.set(play_time_nanos);
            play_time_nanos
        } else {
            self.play_time_offset_nanos.get()
        };
        let local_play_time = play_time_nanos.saturating_sub(offset);
        let spec = self.spec.borrow().clone();
        let initial = self.initial_value.borrow();
        let target = self.target_value.borrow();
        compute_repeatable_value(local_play_time, &initial, &target, spec)
    }

    fn install_subscriber_callback(&self, callback: Rc<dyn Fn()>) {
        if !self.subscriber_callback_installed.replace(true) {
            self.subscriber_callback
                .borrow_mut()
                .replace(callback.clone());
            self.value_state.as_state().on_subscriber(callback);
        }
    }
}

impl<T: Lerp + Clone + PartialEq + 'static> InfiniteTransitionAnimation
    for TransitionAnimationState<T>
{
    fn on_frame(&self, play_time_nanos: u64) {
        let value = self.compute_value(play_time_nanos);
        self.value_state.set(value);
    }

    fn has_subscribers(&self) -> bool {
        self.value_state.as_state().has_subscribers()
    }
}

fn compute_repeatable_value<T: Lerp + Clone>(
    play_time_nanos: u64,
    initial: &T,
    target: &T,
    spec: InfiniteRepeatableSpec<T>,
) -> T {
    let duration_ms = spec.animation.duration_millis.max(1) as i64;
    let delay_ms = spec.animation.delay_millis as i64;
    let mut play_time_ms = (play_time_nanos / 1_000_000) as i64;

    match spec.initial_start_offset.offset_type {
        StartOffsetType::Delay => {
            play_time_ms -= spec.initial_start_offset.offset_millis;
        }
        StartOffsetType::FastForward => {
            play_time_ms += spec.initial_start_offset.offset_millis;
        }
    }

    if play_time_ms < 0 {
        return initial.clone();
    }

    let iteration_duration = (delay_ms + duration_ms).max(1);
    let iteration = play_time_ms / iteration_duration;
    let iteration_time = play_time_ms % iteration_duration;

    let reverse = matches!(spec.repeat_mode, RepeatMode::Reverse) && iteration % 2 != 0;
    let (start, end) = if reverse {
        (target, initial)
    } else {
        (initial, target)
    };

    if iteration_time < delay_ms {
        return start.clone();
    }

    let linear_progress = ((iteration_time - delay_ms) as f32 / duration_ms as f32).clamp(0.0, 1.0);
    let eased = spec.animation.easing.transform(linear_progress);
    start.lerp(end, eased)
}

#[derive(Clone)]
pub struct InfiniteTransition {
    inner: Rc<InfiniteTransitionInner>,
}

struct InfiniteTransitionInner {
    label: String,
    animations: RefCell<Vec<Rc<dyn InfiniteTransitionAnimation>>>,
    run_token: OwnedMutableState<u64>,
    restart_pending: Cell<bool>,
    origin_nanos: Cell<Option<u64>>,
    runtime: RuntimeHandle,
}

impl InfiniteTransition {
    fn new(label: &str, runtime: RuntimeHandle) -> Self {
        Self {
            inner: Rc::new(InfiniteTransitionInner {
                label: label.to_string(),
                animations: RefCell::new(Vec::new()),
                run_token: OwnedMutableState::with_runtime(0u64, runtime.clone()),
                restart_pending: Cell::new(false),
                origin_nanos: Cell::new(None),
                runtime,
            }),
        }
    }

    pub fn label(&self) -> &str {
        &self.inner.label
    }

    #[track_caller]
    fn run(&self) {
        let run_key = self.inner.run_token.get();
        cranpose_core::label_next_ui_task(format!("loop {}", self.inner.label));
        let weak: Weak<InfiniteTransitionInner> = Rc::downgrade(&self.inner);
        cranpose_core::__launched_effect_async_impl(
            cranpose_core::caller_location_key()
                ^ cranpose_core::location_key(file!(), line!(), column!()),
            std::panic::Location::caller().into(),
            run_key,
            move |scope| {
                Box::pin(async move {
                    let clock = scope.runtime().frame_clock();

                    loop {
                        if !scope.is_active() {
                            break;
                        }

                        let Some(inner) = weak.upgrade() else {
                            break;
                        };
                        inner.restart_pending.set(false);

                        if inner.animations.borrow().is_empty() || !inner.has_subscribers() {
                            break;
                        }

                        let now = clock.next_perpetual_frame().await;
                        if !scope.is_active() {
                            break;
                        }

                        inner.on_frame(inner.play_time(now));
                    }
                })
            },
        );
    }

    #[allow(non_snake_case)]
    #[track_caller]
    pub fn animateFloat(
        &self,
        initial_value: f32,
        target_value: f32,
        animation_spec: InfiniteRepeatableSpec<f32>,
        label: &str,
    ) -> State<f32> {
        let _ = label;
        self.animateValue(initial_value, target_value, animation_spec)
    }

    #[allow(non_snake_case)]
    #[track_caller]
    pub fn animateValue<T: Lerp + Clone + PartialEq + 'static>(
        &self,
        initial_value: T,
        target_value: T,
        animation_spec: InfiniteRepeatableSpec<T>,
    ) -> State<T> {
        let caller = cranpose_core::caller_location_key();
        let runtime = with_current_composer(|composer| composer.runtime_handle());
        let initial_for_remember = initial_value.clone();
        let target_for_remember = target_value.clone();
        let spec_for_remember = animation_spec.clone();
        let animation_state = cranpose_core::remember(move || {
            Rc::new(TransitionAnimationState::new(
                initial_for_remember,
                target_for_remember,
                spec_for_remember,
                runtime.clone(),
            ))
        })
        .with(Rc::clone);

        let animation_state_for_effect = Rc::clone(&animation_state);
        let spec_for_effect = animation_spec;
        SideEffect(move || {
            animation_state_for_effect.update_values(
                initial_value.clone(),
                target_value.clone(),
                spec_for_effect,
            );
        });

        let animation_any: Rc<dyn InfiniteTransitionAnimation> = animation_state.clone();
        let transition_inner = Rc::clone(&self.inner);
        let transition_for_subscriber = Rc::downgrade(&transition_inner);
        animation_state.install_subscriber_callback(Rc::new(move || {
            if let Some(transition) = transition_for_subscriber.upgrade() {
                transition.request_restart();
            }
        }));
        let animation_id = Rc::as_ptr(&animation_state) as usize;
        cranpose_core::__disposable_effect_impl(
            caller ^ cranpose_core::location_key(file!(), line!(), column!()),
            animation_id,
            move |_scope| {
                transition_inner.add_animation(animation_any.clone());
                let transition_inner = Rc::clone(&transition_inner);
                let animation_any = animation_any.clone();
                DisposableEffectResult::new(move || {
                    transition_inner.remove_animation(&animation_any);
                })
            },
        );

        animation_state.state()
    }
}

impl InfiniteTransitionInner {
    /// Play time measured from the first frame this transition ever saw.
    /// The driving loop stops while nothing reads its values and starts
    /// again when a reader returns; every animation's play-time offset was
    /// captured on this one timeline, so a restarted loop must keep it.
    fn play_time(&self, now_nanos: u64) -> u64 {
        let origin = match self.origin_nanos.get() {
            Some(origin) => origin,
            None => {
                self.origin_nanos.set(Some(now_nanos));
                now_nanos
            }
        };
        now_nanos.saturating_sub(origin)
    }

    fn add_animation(&self, animation: Rc<dyn InfiniteTransitionAnimation>) {
        let mut list = self.animations.borrow_mut();
        let was_empty = list.is_empty();
        let already_present = list.iter().any(|item| Rc::ptr_eq(item, &animation));
        if !already_present {
            list.push(animation);
        }
        if was_empty && !list.is_empty() {
            self.run_token
                .update(|value| *value = value.wrapping_add(1));
        }
    }

    fn remove_animation(&self, animation: &Rc<dyn InfiniteTransitionAnimation>) {
        let mut list = self.animations.borrow_mut();
        let was_empty = list.is_empty();
        if let Some(index) = list.iter().position(|item| Rc::ptr_eq(item, animation)) {
            list.remove(index);
        }
        let is_empty = list.is_empty();
        drop(list);

        if !was_empty && is_empty {
            self.run_token
                .update(|value| *value = value.wrapping_add(1));
        }
    }

    fn on_frame(&self, play_time_nanos: u64) {
        let animations = self.animations.borrow().clone();
        for animation in animations {
            animation.on_frame(play_time_nanos);
        }
    }

    fn has_subscribers(&self) -> bool {
        self.animations
            .borrow()
            .iter()
            .any(|animation| animation.has_subscribers())
    }

    fn request_restart(self: Rc<Self>) {
        if self.restart_pending.replace(true) {
            return;
        }
        let runtime = self.runtime.clone();
        runtime.enqueue_ui_task(Box::new(move || {
            self.run_token
                .update(|value| *value = value.wrapping_add(1));
        }));
    }
}

#[allow(non_snake_case)]
#[track_caller]
pub fn rememberInfiniteTransition(label: &str) -> InfiniteTransition {
    let runtime = with_current_composer(|composer| composer.runtime_handle());
    let transition =
        cranpose_core::remember(move || InfiniteTransition::new(label, runtime.clone()))
            .with(|transition| transition.clone());
    transition.run();
    transition
}

/// Generic animatable value holder.
pub struct Animatable<T: SpringScalar + 'static> {
    inner: Rc<RefCell<AnimatableInner<T>>>,
}

struct AnimatableInner<T: SpringScalar + 'static> {
    state: OwnedMutableState<T>,
    runtime: RuntimeHandle,
    current: T,
    velocity: [f32; SPRING_MAX_DIMENSIONS],
    start: T,
    target: T,
    animation_type: AnimationType,
    start_time_nanos: Option<u64>,
    last_frame_nanos: Option<u64>,
    sampled_time_nanos: Option<u64>,
    registration: Option<FrameCallbackRegistration>,
}

impl<T: SpringScalar + 'static> Animatable<T> {
    /// Create a new animatable with the given initial value.
    pub fn new(initial: T, runtime: RuntimeHandle) -> Self {
        Self::new_with_animation(initial, AnimationType::default(), runtime)
    }

    /// Create a new animatable already at rest at `initial`, recording
    /// `animation` as the spec currently driving it without scheduling a
    /// frame.
    ///
    /// Building blocks like [`crate::animateValueAsState`] use this instead
    /// of [`Animatable::new`] so that a call site's first render, which
    /// starts already at its target, does not spuriously detect the
    /// caller's spec as "changed" the moment [`Animatable::animation_type`]
    /// is first compared against it (a fresh [`Animatable::new`] always
    /// reports [`AnimationType::default`], regardless of what the call site
    /// actually asked for) and schedule a pointless one-frame animation to
    /// nowhere.
    pub fn new_with_animation(
        initial: T,
        animation: AnimationType,
        runtime: RuntimeHandle,
    ) -> Self {
        let inner = AnimatableInner {
            state: OwnedMutableState::with_runtime_structural_eq(initial.clone(), runtime.clone()),
            runtime,
            current: initial.clone(),
            velocity: [0.0; SPRING_MAX_DIMENSIONS],
            start: initial.clone(),
            target: initial,
            animation_type: animation,
            start_time_nanos: None,
            last_frame_nanos: None,
            sampled_time_nanos: None,
            registration: None,
        };
        Self {
            inner: Rc::new(RefCell::new(inner)),
        }
    }

    /// Animate to the target value using the specified animation.
    ///
    /// Retargeting mid-flight keeps the in-flight velocity (springs continue
    /// their physical motion toward the new target).
    pub fn animateTo(&mut self, target: T, animation: AnimationType) {
        self.start_animation(target, animation, None);
    }

    /// Retarget at an input timestamp on the shared animation clock.
    /// Advances the previous animation to that boundary before preserving its velocity
    /// and starting the new target. Older timestamps use the latest sampled time.
    pub fn animate_to_at(&mut self, target: T, animation: AnimationType, time_nanos: u64) {
        let time = {
            let mut inner = self.inner.borrow_mut();
            let time = time_nanos.max(inner.sampled_time_nanos.unwrap_or(0));
            if inner.registration.is_some() {
                Self::advance_inner(&mut inner, time);
            }
            inner.sampled_time_nanos = Some(time);
            time
        };
        self.start_animation(target, animation, Some(time));
    }

    fn start_animation(
        &mut self,
        target: T,
        animation: AnimationType,
        exact_start_time_nanos: Option<u64>,
    ) {
        {
            let mut inner = self.inner.borrow_mut();
            let previous_animation = inner.animation_type;

            if let Some(registration) = inner.registration.take() {
                registration.cancel();
            }

            inner.start = inner.current.clone();
            inner.target = target;
            inner.animation_type = animation;
            inner.start_time_nanos = exact_start_time_nanos;
            match animation {
                AnimationType::Spring(spec) => {
                    let continues_spring = matches!(previous_animation, AnimationType::Spring(_));
                    if let Some(start_time_nanos) = exact_start_time_nanos {
                        let delay_nanos = spec.delay_millis.saturating_mul(1_000_000);
                        inner.last_frame_nanos = Some(start_time_nanos.saturating_add(delay_nanos));
                    } else if !continues_spring {
                        inner.last_frame_nanos = None;
                    }
                }
                AnimationType::Tween(_) => {
                    inner.last_frame_nanos = None;
                    inner.velocity = [0.0; SPRING_MAX_DIMENSIONS];
                }
            }
        }

        Self::schedule_frame(&self.inner);
    }

    /// Animate to `target`, seeding the spring with `velocity` (value units
    /// per second, per dimension) — the gesture-handoff entry point: pass the
    /// release velocity so the animation continues the finger's motion.
    pub fn animate_to_with_velocity(&mut self, target: T, velocity: T, animation: AnimationType) {
        {
            let mut inner = self.inner.borrow_mut();
            for index in 0..T::DIMENSIONS.min(SPRING_MAX_DIMENSIONS) {
                inner.velocity[index] = velocity.dimension(index);
            }
        }
        self.animateTo(target, animation);
    }

    /// Animate from an exact point on the shared frame clock. The first
    /// rendered spring sample integrates every elapsed nanosecond since this
    /// boundary, so input-to-animation handoff is independent of which vsync
    /// first services the callback.
    pub fn animate_to_with_velocity_at(
        &mut self,
        target: T,
        velocity: T,
        animation: AnimationType,
        start_time_nanos: u64,
    ) {
        {
            let mut inner = self.inner.borrow_mut();
            for index in 0..T::DIMENSIONS.min(SPRING_MAX_DIMENSIONS) {
                inner.velocity[index] = velocity.dimension(index);
            }
        }
        self.start_animation(target, animation, Some(start_time_nanos));
    }

    /// The current velocity in value units per second (zero when settled).
    pub fn velocity(&self) -> T {
        T::from_dimensions(self.inner.borrow().velocity)
    }

    /// Return the current animation target.
    pub fn target(&self) -> T {
        self.inner.borrow().target.clone()
    }

    /// Return the animation spec currently driving this animatable.
    pub fn animation_type(&self) -> AnimationType {
        self.inner.borrow().animation_type
    }

    /// Whether a frame callback is currently scheduled: `true` while the
    /// value is mid-flight toward its target, `false` once it has settled.
    /// Mirrors Jetpack Compose's `Animatable.isRunning`.
    pub fn is_running(&self) -> bool {
        self.inner.borrow().registration.is_some()
    }

    /// Pointer identity of the shared inner state, stable across clones of
    /// the same [`Animatable`]. Used to key registration into a parent
    /// collection (e.g. [`crate::transition::Transition`]'s children) by
    /// object identity rather than value equality.
    pub(crate) fn identity(&self) -> usize {
        Rc::as_ptr(&self.inner) as usize
    }

    /// Get the current state.
    pub fn state(&self) -> State<T> {
        self.inner.borrow().state.as_state()
    }

    /// Snap immediately to the target value without animating.
    pub fn snapTo(&mut self, target: T) {
        let mut inner = self.inner.borrow_mut();
        if let Some(registration) = inner.registration.take() {
            registration.cancel();
        }
        inner.current = target.clone();
        inner.start = target.clone();
        inner.target = target.clone();
        inner.start_time_nanos = None;
        inner.last_frame_nanos = None;
        inner.velocity = [0.0; SPRING_MAX_DIMENSIONS];
        inner.state.set_value(target);
    }

    fn schedule_frame(this: &Rc<RefCell<AnimatableInner<T>>>) {
        let runtime = {
            let inner = this.borrow();
            if inner.registration.is_some() {
                return;
            }
            inner.runtime.clone()
        };
        let weak = Rc::downgrade(this);
        let registration = runtime.frame_clock().with_frame_nanos(move |time| {
            if let Some(strong) = weak.upgrade() {
                Self::on_frame(&strong, time);
            }
        });
        this.borrow_mut().registration = Some(registration);
    }

    fn on_frame(this: &Rc<RefCell<AnimatableInner<T>>>, frame_time_nanos: u64) {
        let schedule_next = {
            let mut inner = this.borrow_mut();
            inner.registration = None;
            Self::advance_inner(&mut inner, frame_time_nanos)
        };
        if schedule_next {
            Self::schedule_frame(this);
        }
    }

    fn advance_inner(inner: &mut AnimatableInner<T>, frame_time_nanos: u64) -> bool {
        let frame_time_nanos = frame_time_nanos.max(inner.sampled_time_nanos.unwrap_or(0));
        inner.sampled_time_nanos = Some(frame_time_nanos);
        let mut schedule_next = false;
        match inner.animation_type {
            AnimationType::Tween(spec) => {
                let start_time = inner.start_time_nanos.get_or_insert(frame_time_nanos);
                let elapsed_nanos = frame_time_nanos.saturating_sub(*start_time);
                let delay_nanos = spec.delay_millis.saturating_mul(1_000_000);

                if elapsed_nanos < delay_nanos {
                    schedule_next = true;
                } else {
                    let animation_elapsed = elapsed_nanos - delay_nanos;
                    let duration_nanos = spec.duration_millis * 1_000_000;
                    let duration_nanos = duration_nanos.max(1);
                    let linear_progress =
                        (animation_elapsed as f32 / duration_nanos as f32).clamp(0.0, 1.0);
                    let progress = spec.easing.transform(linear_progress);

                    let new_value = inner.start.lerp(&inner.target, progress);
                    inner.current = new_value.clone();
                    inner.state.set_value(new_value);

                    if linear_progress >= 1.0 {
                        inner.current = inner.target.clone();
                        inner.start = inner.target.clone();
                        inner.start_time_nanos = None;
                        inner.state.set_value(inner.target.clone());
                    } else {
                        schedule_next = true;
                    }
                }
            }
            AnimationType::Spring(spec) => {
                let start_time = inner.start_time_nanos.get_or_insert(frame_time_nanos);
                let elapsed_nanos = frame_time_nanos.saturating_sub(*start_time);
                let delay_nanos = spec.delay_millis.saturating_mul(1_000_000);
                if elapsed_nanos < delay_nanos {
                    inner.last_frame_nanos = Some(start_time.saturating_add(delay_nanos));
                    schedule_next = true;
                } else {
                    let last = inner.last_frame_nanos.replace(frame_time_nanos);
                    let dt = last
                        .map(|last| frame_time_nanos.saturating_sub(last) as f32 / 1_000_000_000.0)
                        .unwrap_or(0.0);

                    if dt <= 0.0 {
                        schedule_next = true;
                    } else {
                        let dimensions = T::DIMENSIONS.min(SPRING_MAX_DIMENSIONS);
                        let mut position = [0.0f32; SPRING_MAX_DIMENSIONS];
                        for (index, slot) in position.iter_mut().enumerate().take(dimensions) {
                            let value = inner.current.dimension(index);
                            let target = inner.target.dimension(index);
                            let (next_value, next_velocity) = advance_spring(
                                value,
                                inner.velocity[index],
                                target,
                                spec.damping_ratio,
                                spec.stiffness,
                                dt,
                            );
                            *slot = next_value;
                            inner.velocity[index] = next_velocity;
                        }

                        inner.current = T::from_dimensions(position);
                        inner.state.set_value(inner.current.clone());

                        let settled = (0..dimensions).all(|index| {
                            inner.velocity[index].abs() < spec.velocity_threshold
                                && (position[index] - inner.target.dimension(index)).abs()
                                    < spec.position_threshold
                        });

                        if settled {
                            inner.current = inner.target.clone();
                            inner.start = inner.target.clone();
                            inner.start_time_nanos = None;
                            inner.last_frame_nanos = None;
                            inner.velocity = [0.0; SPRING_MAX_DIMENSIONS];
                            inner.state.set_value(inner.target.clone());
                        } else {
                            schedule_next = true;
                        }
                    }
                }
            }
        }
        schedule_next
    }
}

/// [`animateFloatAsState`] with an explicit initial value: the first
/// composition seeds the animation at `initial` and animates toward `target`,
/// so newly appearing content can enter from 0 instead of snapping. The
/// building block for enter transitions (`Crossfade`, `AnimatedVisibility`,
/// morphing popups).
#[track_caller]
pub fn animate_float_as_state_with_initial(
    initial: f32,
    target: f32,
    animation: AnimationType,
    label: &str,
) -> State<f32> {
    let _ = label;
    let caller = cranpose_core::caller_location_key();
    with_current_composer(|composer| {
        let runtime = composer.runtime_handle();
        let anim: Owned<Animatable<f32>> =
            composer.remember_at(caller, || Animatable::new(initial, runtime));
        anim.update(|animatable| {
            let is_new_target = (animatable.target() - target).abs() > f32::EPSILON;
            let is_new_animation = animatable.animation_type() != animation;
            if is_new_target || is_new_animation {
                animatable.animateTo(target, animation);
            }
        });
        anim.with(|animatable| animatable.state())
    })
}

/// Generic building block for the whole `animate*AsState` family: any type
/// that implements [`SpringScalar`] (the vector-converter core -- equality
/// plus a fixed-size float decomposition, mirroring Compose's
/// `TwoWayConverter`/`AnimationVector`) gets a fire-and-forget animation for
/// free. [`animateFloatAsState`], [`crate::animateColorAsState`] and the
/// `Dp`/`Offset`/`Size`/`Rect` specializations in
/// [`crate::unit_animation`]/[`crate::geometry_animation`] are all thin
/// wrappers over this one function.
#[track_caller]
pub fn animateValueAsState<T: SpringScalar + PartialEq + 'static>(
    target: T,
    animation: AnimationType,
    label: &str,
) -> State<T> {
    let _ = label;
    let caller = cranpose_core::caller_location_key();
    with_current_composer(|composer| {
        let runtime = composer.runtime_handle();
        let anim: Owned<Animatable<T>> = composer.remember_at(caller, || {
            Animatable::new_with_animation(target.clone(), animation, runtime)
        });
        anim.update(|animatable| {
            let is_new_target = animatable.target() != target;
            let is_new_animation = animatable.animation_type() != animation;
            if is_new_target || is_new_animation {
                animatable.animateTo(target.clone(), animation);
            }
        });
        anim.with(|animatable| animatable.state())
    })
}

#[allow(non_snake_case)]
#[track_caller]
pub fn animateFloatAsState(target: f32, animation: AnimationType, label: &str) -> State<f32> {
    animateValueAsState(target, animation, label)
}

impl<T: SpringScalar + 'static> Clone for Animatable<T> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
        }
    }
}

#[cfg(test)]
#[path = "tests/animation_tests.rs"]
mod tests;