plushie 0.7.1

Desktop GUI framework for Rust
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
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
//! SDK-side frame-by-frame animation.
//!
//! [`Tween`] provides stateful interpolation driven by the app's
//! update loop. Use for animations that need to be tied to model
//! state (e.g., canvas-based custom rendering).
//!
//! Two modes are supported:
//!
//! - **Timed**: easing-curve interpolation over a fixed duration.
//! - **Spring**: damped harmonic oscillator physics simulation.
//!
//! For declarative property animations that the renderer handles
//! autonomously, use [`Transition`](super::Transition) or
//! [`Spring`](super::Spring) instead.

use super::{Easing, Repeat};

use std::f64::consts::PI;

// ---------------------------------------------------------------------------
// SpringConfig
// ---------------------------------------------------------------------------

/// Physics parameters for spring-based animation.
///
/// ```
/// use plushie::animation::SpringConfig;
///
/// // Use a preset
/// let config = SpringConfig::bouncy();
///
/// // Or customize from defaults
/// let config = SpringConfig::default()
///     .stiffness(250.0)
///     .damping(18.0);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SpringConfig {
    /// Spring stiffness (force per unit displacement). Higher values
    /// produce faster, snappier motion. Default: 100.0.
    pub stiffness: f64,
    /// Damping coefficient (force per unit velocity). Higher values
    /// reduce overshoot and oscillation. Default: 10.0.
    pub damping: f64,
    /// Mass of the animated object. Higher values produce slower,
    /// heavier motion. Must be positive (zero causes division by
    /// zero in the physics simulation). Default: 1.0.
    pub mass: f64,
    /// Initial velocity at the start of the animation. Default: 0.0.
    pub initial_velocity: f64,
}

impl Default for SpringConfig {
    fn default() -> Self {
        Self {
            stiffness: 100.0,
            damping: 10.0,
            mass: 1.0,
            initial_velocity: 0.0,
        }
    }
}

impl SpringConfig {
    /// Slow, smooth motion with no overshoot.
    pub fn gentle() -> Self {
        Self {
            stiffness: 120.0,
            damping: 14.0,
            ..Self::default()
        }
    }

    /// Quick motion with visible overshoot.
    pub fn bouncy() -> Self {
        Self {
            stiffness: 300.0,
            damping: 10.0,
            ..Self::default()
        }
    }

    /// Very quick, crisp stop with minimal overshoot.
    pub fn stiff() -> Self {
        Self {
            stiffness: 400.0,
            damping: 30.0,
            ..Self::default()
        }
    }

    /// Quick with minimal overshoot. A balanced default.
    pub fn snappy() -> Self {
        Self {
            stiffness: 200.0,
            damping: 20.0,
            ..Self::default()
        }
    }

    /// Slow, heavy, deliberate motion.
    pub fn molasses() -> Self {
        Self {
            stiffness: 60.0,
            damping: 12.0,
            ..Self::default()
        }
    }

    /// Override the stiffness value.
    pub fn stiffness(mut self, v: f64) -> Self {
        self.stiffness = v;
        self
    }
    /// Override the damping value.
    pub fn damping(mut self, v: f64) -> Self {
        self.damping = v;
        self
    }
    /// Override the mass value. Must be positive.
    pub fn mass(mut self, v: f64) -> Self {
        self.mass = v;
        self
    }
    /// Set the initial velocity for the animation.
    pub fn initial_velocity(mut self, v: f64) -> Self {
        self.initial_velocity = v;
        self
    }
}

// ---------------------------------------------------------------------------
// RedirectOpts
// ---------------------------------------------------------------------------

/// Optional parameter overrides for [`Tween::redirect_with`].
///
/// Only applies to timed tweens; ignored for spring tweens.
///
/// ```
/// use plushie::animation::{RedirectOpts, Easing};
///
/// let opts = RedirectOpts::default()
///     .easing(Easing::EaseOutCubic)
///     .duration(300);
/// ```
#[derive(Debug, Clone, Default)]
pub struct RedirectOpts {
    /// Override the easing curve for the redirected animation.
    pub easing: Option<Easing>,
    /// Override the duration (ms) for the redirected animation.
    pub duration: Option<u64>,
}

impl RedirectOpts {
    /// Override the easing curve.
    pub fn easing(mut self, e: Easing) -> Self {
        self.easing = Some(e);
        self
    }
    /// Override the duration in milliseconds.
    pub fn duration(mut self, d: u64) -> Self {
        self.duration = Some(d);
        self
    }
}

// ---------------------------------------------------------------------------
// Internal mode
// ---------------------------------------------------------------------------

#[derive(Debug, Clone)]
enum TweenMode {
    Timed {
        duration_ms: u64,
        easing: Easing,
        delay_ms: u64,
    },
    Spring {
        config: SpringConfig,
        velocity: f64,
    },
}

// ---------------------------------------------------------------------------
// Tween
// ---------------------------------------------------------------------------

/// A stateful interpolator for frame-by-frame animation.
///
/// ## Timed mode
///
/// Interpolates from `from` to `to` over a fixed duration using an
/// easing curve. Supports delay, repeat, and auto-reverse.
///
/// ```
/// use plushie::animation::{Tween, Easing};
///
/// let mut tween = Tween::new(0.0, 100.0, 500)
///     .easing(Easing::EaseOutCubic);
///
/// tween.start(0);
/// tween.advance(250);
/// assert!(tween.value().is_some());
/// assert!(!tween.finished());
///
/// tween.advance(500);
/// assert!(tween.finished());
/// ```
///
/// ## Spring mode
///
/// Uses a damped harmonic oscillator to animate toward the target.
/// Duration is implicit: the animation finishes when the spring
/// settles. Repeat and auto-reverse are not supported.
///
/// ```
/// use plushie::animation::{Tween, SpringConfig};
///
/// let mut tween = Tween::spring(0.0, 100.0, SpringConfig::bouncy());
///
/// tween.start(0);
/// tween.advance(500);
/// assert!(tween.running());
/// ```
#[derive(Debug, Clone)]
pub struct Tween {
    /// Starting value of the tween.
    pub from: f64,
    /// Target value at the end of the tween.
    pub to: f64,
    mode: TweenMode,
    /// Optional loop policy.
    pub repeat: Option<Repeat>,
    /// When true, each loop iteration reverses direction (ping-pong).
    pub auto_reverse: bool,
    started_at: Option<u64>,
    /// Timestamp of the last `advance` call. Only meaningful in spring
    /// mode; the timed mode reads `started_at` for elapsed-time math
    /// and does not update this field. `restart_cycle` therefore
    /// leaves `last_timestamp` alone in timed mode by design.
    last_timestamp: Option<u64>,
    value: Option<f64>,
    finished: bool,
}

impl Tween {
    // -- Timed constructors --------------------------------------------------

    /// Create a timed tween from `from` to `to` over `duration_ms` milliseconds.
    pub fn new(from: f64, to: f64, duration_ms: u64) -> Self {
        Self {
            from,
            to,
            mode: TweenMode::Timed {
                duration_ms,
                easing: Easing::EaseInOut,
                delay_ms: 0,
            },
            repeat: None,
            auto_reverse: false,
            started_at: None,
            last_timestamp: None,
            value: None,
            finished: false,
        }
    }

    /// Set the easing curve (timed mode only, no-op for spring).
    pub fn easing(mut self, e: Easing) -> Self {
        if let TweenMode::Timed { easing, .. } = &mut self.mode {
            *easing = e;
        }
        self
    }

    /// Set the delay before the animation starts (timed mode only).
    pub fn delay(mut self, ms: u64) -> Self {
        if let TweenMode::Timed { delay_ms, .. } = &mut self.mode {
            *delay_ms = ms;
        }
        self
    }

    /// Set the animation duration in milliseconds (timed mode only).
    pub fn duration(mut self, ms: u64) -> Self {
        if let TweenMode::Timed { duration_ms, .. } = &mut self.mode {
            *duration_ms = ms;
        }
        self
    }

    /// Set a finite repeat count (applies to timed mode only).
    pub fn repeat(mut self, n: u32) -> Self {
        self.repeat = Some(Repeat::Times(n));
        self
    }

    /// Repeat forever (applies to timed mode only).
    pub fn repeat_forever(mut self) -> Self {
        self.repeat = Some(Repeat::Forever);
        self
    }

    /// Reverse direction on each repeat (applies to timed mode only).
    pub fn auto_reverse(mut self, v: bool) -> Self {
        self.auto_reverse = v;
        self
    }

    /// Create a looping tween (repeat forever, auto-reverse).
    pub fn looping(from: f64, to: f64, duration_ms: u64) -> Self {
        Self::new(from, to, duration_ms)
            .repeat_forever()
            .auto_reverse(true)
    }

    // -- Spring constructor --------------------------------------------------

    /// Create a spring-physics tween from `from` toward `to`.
    ///
    /// The animation finishes when the spring settles (velocity and
    /// position error are both negligible). Duration is implicit.
    ///
    /// # Panics
    ///
    /// Panics if `config.mass` is zero, negative, NaN, or infinite.
    pub fn spring(from: f64, to: f64, config: SpringConfig) -> Self {
        assert!(
            config.mass.is_finite() && config.mass > 0.0,
            "spring mass must be a positive finite number, got {}",
            config.mass
        );

        let velocity = config.initial_velocity;
        Self {
            from,
            to,
            mode: TweenMode::Spring { config, velocity },
            repeat: None,
            auto_reverse: false,
            started_at: None,
            last_timestamp: None,
            value: None,
            finished: false,
        }
    }

    // -- Lifecycle -----------------------------------------------------------

    /// Start the tween at the given timestamp (monotonic milliseconds).
    pub fn start(&mut self, timestamp: u64) {
        self.started_at = Some(timestamp);
        self.last_timestamp = Some(timestamp);
        self.value = Some(self.from);
        self.finished = false;
    }

    /// Start only if not already started.
    pub fn start_once(&mut self, timestamp: u64) {
        if self.started_at.is_none() {
            self.start(timestamp);
        }
    }

    /// Advance the tween to the given timestamp.
    pub fn advance(&mut self, timestamp: u64) {
        if self.started_at.is_none() || self.finished {
            return;
        }

        match &self.mode {
            TweenMode::Timed { .. } => self.advance_timed(timestamp),
            TweenMode::Spring { .. } => self.advance_spring(timestamp),
        }
    }

    /// Redirect the tween to a new target from the current value.
    ///
    /// For spring tweens, velocity is preserved for natural momentum.
    /// For timed tweens, the animation restarts with the current
    /// easing and duration.
    pub fn redirect(&mut self, to: f64, timestamp: u64) {
        self.redirect_inner(to, timestamp, None);
    }

    /// Redirect with optional easing/duration overrides (timed only).
    ///
    /// Spring tweens ignore the options; velocity is always preserved.
    pub fn redirect_with(&mut self, to: f64, timestamp: u64, opts: RedirectOpts) {
        self.redirect_inner(to, timestamp, Some(opts));
    }

    fn redirect_inner(&mut self, to: f64, timestamp: u64, opts: Option<RedirectOpts>) {
        let current = self.value.unwrap_or(self.from);
        self.from = current;
        self.to = to;

        if let Some(opts) = opts
            && let TweenMode::Timed {
                easing,
                duration_ms,
                ..
            } = &mut self.mode
        {
            if let Some(e) = opts.easing {
                *easing = e;
            }
            if let Some(d) = opts.duration {
                *duration_ms = d;
            }
        }

        self.start(timestamp);
        // For springs, start() resets started_at and last_timestamp
        // but does NOT touch velocity (it lives in TweenMode::Spring).
    }

    // -- Queries -------------------------------------------------------------

    /// The current interpolated value, or `None` if not started.
    pub fn value(&self) -> Option<f64> {
        self.value
    }

    /// Whether the tween has reached its end value.
    pub fn finished(&self) -> bool {
        self.finished
    }

    /// Whether the tween has been started and is not yet finished.
    pub fn running(&self) -> bool {
        self.started_at.is_some() && !self.finished
    }

    /// Whether this is a spring-mode tween.
    pub fn is_spring(&self) -> bool {
        matches!(self.mode, TweenMode::Spring { .. })
    }

    // -- Internal: timed advance ---------------------------------------------

    fn advance_timed(&mut self, timestamp: u64) {
        let started = self.started_at.unwrap();
        let TweenMode::Timed {
            duration_ms,
            easing,
            delay_ms,
        } = &self.mode
        else {
            return;
        };
        let duration_ms = *duration_ms;
        let delay_ms = *delay_ms;
        let easing = *easing;

        let elapsed = timestamp.saturating_sub(started);
        if elapsed < delay_ms {
            self.value = Some(self.from);
            return;
        }

        let active_elapsed = elapsed - delay_ms;
        if active_elapsed >= duration_ms {
            self.handle_cycle_end();
            return;
        }

        let t = active_elapsed as f64 / duration_ms as f64;
        let eased_t = apply_easing(t, &easing);
        self.value = Some(self.from + (self.to - self.from) * eased_t);
    }

    /// Handle the end of one timed animation cycle.
    fn handle_cycle_end(&mut self) {
        match self.repeat {
            None => {
                self.value = Some(self.to);
                self.finished = true;
            }
            Some(Repeat::Forever) => {
                self.restart_cycle();
            }
            Some(Repeat::Times(n)) if n > 1 => {
                self.repeat = Some(Repeat::Times(n - 1));
                self.restart_cycle();
            }
            Some(Repeat::Times(_)) => {
                self.value = Some(self.to);
                self.finished = true;
            }
        }
    }

    fn restart_cycle(&mut self) {
        if let Some(started) = self.started_at
            && let TweenMode::Timed { duration_ms, .. } = &self.mode
        {
            self.started_at = Some(started + duration_ms);
        }
        if self.auto_reverse {
            std::mem::swap(&mut self.from, &mut self.to);
        } else {
            self.value = Some(self.from);
        }
    }

    // -- Internal: spring advance --------------------------------------------

    fn advance_spring(&mut self, timestamp: u64) {
        let last = self.last_timestamp.unwrap_or(timestamp);
        let elapsed_ms = timestamp.saturating_sub(last);
        self.last_timestamp = Some(timestamp);

        if elapsed_ms == 0 {
            return;
        }

        let TweenMode::Spring { config, velocity } = &mut self.mode else {
            return;
        };

        let mut pos = self.value.unwrap_or(self.from);
        let mut vel = *velocity;

        // Fixed 1ms timestep Euler integration for numerical stability.
        // Capped at 1000 steps per advance to prevent runaway loops
        // on large time deltas (matches Elixir implementation).
        let dt: f64 = 0.001;
        let steps = elapsed_ms.min(1000);
        for _ in 0..steps {
            let force = -config.stiffness * (pos - self.to) - config.damping * vel;
            let acc = force / config.mass;
            vel += acc * dt;
            pos += vel * dt;

            if !pos.is_finite() || !vel.is_finite() {
                pos = self.to;
                vel = 0.0;
                self.finished = true;
                break;
            }
        }

        // Convergence: spring has settled when both velocity and
        // position error are negligible.
        if vel.abs() < 0.01 && (pos - self.to).abs() < 0.001 {
            pos = self.to;
            vel = 0.0;
            self.finished = true;
        }

        self.value = Some(pos);
        *velocity = vel;
    }
}

// ---------------------------------------------------------------------------
// Easing function dispatch
// ---------------------------------------------------------------------------

/// Maps an Easing variant to the actual easing curve function.
///
/// All curves match the standard CSS/easings.net definitions and
/// are consistent with `Plushie.Animation.Easing` on the Elixir side.
fn apply_easing(t: f64, easing: &Easing) -> f64 {
    // Back overshoot constants (standard CSS values)
    const C1: f64 = 1.70158;
    const C2: f64 = C1 * 1.525;
    const C3: f64 = C1 + 1.0;

    // Elastic constants
    const C4: f64 = 2.0 * PI / 3.0;
    const C5: f64 = 2.0 * PI / 4.5;

    // Bounce constants
    const N1: f64 = 7.5625;
    const D1: f64 = 2.75;

    match easing {
        // Linear
        Easing::Linear => t,

        // Sine
        Easing::EaseIn => 1.0 - (t * PI / 2.0).cos(),
        Easing::EaseOut => (t * PI / 2.0).sin(),
        Easing::EaseInOut => -(PI * t).cos().mul_add(0.5, -0.5),

        // Quadratic
        Easing::EaseInQuad => t * t,
        Easing::EaseOutQuad => 1.0 - (1.0 - t) * (1.0 - t),
        Easing::EaseInOutQuad => {
            if t < 0.5 {
                2.0 * t * t
            } else {
                1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
            }
        }

        // Cubic
        Easing::EaseInCubic => t * t * t,
        Easing::EaseOutCubic => 1.0 - (1.0 - t).powi(3),
        Easing::EaseInOutCubic => {
            if t < 0.5 {
                4.0 * t * t * t
            } else {
                1.0 - (-2.0 * t + 2.0).powi(3) / 2.0
            }
        }

        // Quartic
        Easing::EaseInQuart => t * t * t * t,
        Easing::EaseOutQuart => 1.0 - (1.0 - t).powi(4),
        Easing::EaseInOutQuart => {
            if t < 0.5 {
                8.0 * t * t * t * t
            } else {
                1.0 - (-2.0 * t + 2.0).powi(4) / 2.0
            }
        }

        // Quintic
        Easing::EaseInQuint => t * t * t * t * t,
        Easing::EaseOutQuint => 1.0 - (1.0 - t).powi(5),
        Easing::EaseInOutQuint => {
            if t < 0.5 {
                16.0 * t * t * t * t * t
            } else {
                1.0 - (-2.0 * t + 2.0).powi(5) / 2.0
            }
        }

        // Exponential
        Easing::EaseInExpo => {
            if t == 0.0 {
                0.0
            } else {
                2.0_f64.powf(10.0 * t - 10.0)
            }
        }
        Easing::EaseOutExpo => {
            if t == 1.0 {
                1.0
            } else {
                1.0 - 2.0_f64.powf(-10.0 * t)
            }
        }
        Easing::EaseInOutExpo => {
            if t == 0.0 {
                0.0
            } else if t == 1.0 {
                1.0
            } else if t < 0.5 {
                2.0_f64.powf(20.0 * t - 10.0) / 2.0
            } else {
                (2.0 - 2.0_f64.powf(-20.0 * t + 10.0)) / 2.0
            }
        }

        // Circular
        Easing::EaseInCirc => 1.0 - (1.0 - t * t).sqrt(),
        Easing::EaseOutCirc => (1.0 - (t - 1.0) * (t - 1.0)).sqrt(),
        Easing::EaseInOutCirc => {
            if t < 0.5 {
                (1.0 - (1.0 - (2.0 * t).powi(2)).sqrt()) / 2.0
            } else {
                (1.0 + (1.0 - (-2.0 * t + 2.0).powi(2)).sqrt()) / 2.0
            }
        }

        // Back (overshoot)
        Easing::EaseInBack => C3 * t * t * t - C1 * t * t,
        Easing::EaseOutBack => 1.0 + C3 * (t - 1.0).powi(3) + C1 * (t - 1.0).powi(2),
        Easing::EaseInOutBack => {
            if t < 0.5 {
                (2.0 * t).powi(2) * ((C2 + 1.0) * 2.0 * t - C2) / 2.0
            } else {
                ((2.0 * t - 2.0).powi(2) * ((C2 + 1.0) * (2.0 * t - 2.0) + C2) + 2.0) / 2.0
            }
        }

        // Elastic (oscillating overshoot)
        Easing::EaseInElastic => {
            if t == 0.0 {
                0.0
            } else if t == 1.0 {
                1.0
            } else {
                -(2.0_f64.powf(10.0 * t - 10.0) * ((10.0 * t - 10.75) * C4).sin())
            }
        }
        Easing::EaseOutElastic => {
            if t == 0.0 {
                0.0
            } else if t == 1.0 {
                1.0
            } else {
                2.0_f64.powf(-10.0 * t) * ((10.0 * t - 0.75) * C4).sin() + 1.0
            }
        }
        Easing::EaseInOutElastic => {
            if t == 0.0 {
                0.0
            } else if t == 1.0 {
                1.0
            } else if t < 0.5 {
                -(2.0_f64.powf(20.0 * t - 10.0) * ((20.0 * t - 11.125) * C5).sin()) / 2.0
            } else {
                2.0_f64.powf(-20.0 * t + 10.0) * ((20.0 * t - 11.125) * C5).sin() / 2.0 + 1.0
            }
        }

        // Bounce
        Easing::EaseInBounce => 1.0 - ease_out_bounce(1.0 - t, N1, D1),
        Easing::EaseOutBounce => ease_out_bounce(t, N1, D1),
        Easing::EaseInOutBounce => {
            if t < 0.5 {
                (1.0 - ease_out_bounce(1.0 - 2.0 * t, N1, D1)) / 2.0
            } else {
                (1.0 + ease_out_bounce(2.0 * t - 1.0, N1, D1)) / 2.0
            }
        }

        // Cubic bezier (Newton-Raphson solver)
        Easing::CubicBezier(x1, y1, x2, y2) => {
            cubic_bezier(t, *x1 as f64, *y1 as f64, *x2 as f64, *y2 as f64)
        }
    }
}

/// Bounce ease-out helper (used by all three bounce variants).
fn ease_out_bounce(t: f64, n1: f64, d1: f64) -> f64 {
    if t < 1.0 / d1 {
        n1 * t * t
    } else if t < 2.0 / d1 {
        let t2 = t - 1.5 / d1;
        n1 * t2 * t2 + 0.75
    } else if t < 2.5 / d1 {
        let t2 = t - 2.25 / d1;
        n1 * t2 * t2 + 0.9375
    } else {
        let t2 = t - 2.625 / d1;
        n1 * t2 * t2 + 0.984375
    }
}

/// Evaluate a cubic bezier easing curve using Newton-Raphson iteration.
fn cubic_bezier(t: f64, x1: f64, y1: f64, x2: f64, y2: f64) -> f64 {
    if t <= 0.0 {
        return 0.0;
    }
    if t >= 1.0 {
        return 1.0;
    }

    // Solve for the bezier parameter `s` where bezier_x(s) == t
    let s = newton_raphson_solve(t, x1, x2, t, 8);
    bezier_eval(s, y1, y2)
}

/// Evaluates the cubic bezier polynomial for one axis.
/// B(s) = 3(1-s)^2*s*p1 + 3(1-s)*s^2*p2 + s^3
fn bezier_eval(s: f64, p1: f64, p2: f64) -> f64 {
    let s2 = s * s;
    let s3 = s2 * s;
    3.0 * (1.0 - s) * (1.0 - s) * s * p1 + 3.0 * (1.0 - s) * s2 * p2 + s3
}

/// Derivative of the bezier polynomial for one axis.
fn bezier_derivative(s: f64, p1: f64, p2: f64) -> f64 {
    3.0 * (1.0 - s) * (1.0 - s) * p1 + 6.0 * (1.0 - s) * s * (p2 - p1) + 3.0 * s * s * (1.0 - p2)
}

fn newton_raphson_solve(target_x: f64, x1: f64, x2: f64, mut guess: f64, max_iter: u32) -> f64 {
    for _ in 0..max_iter {
        let x = bezier_eval(guess, x1, x2);
        let dx = bezier_derivative(guess, x1, x2);

        if (x - target_x).abs() < 1.0e-7 || dx.abs() < 1.0e-7 {
            break;
        }
        guess = (guess - (x - target_x) / dx).clamp(0.0, 1.0);
    }
    guess
}

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

    // -- Easing tests --------------------------------------------------------

    #[test]
    fn linear_easing_is_identity() {
        for i in 0..=10 {
            let t = i as f64 / 10.0;
            let result = apply_easing(t, &Easing::Linear);
            assert!((result - t).abs() < 1.0e-10);
        }
    }

    #[test]
    fn ease_in_out_boundaries() {
        assert!((apply_easing(0.0, &Easing::EaseInOut)).abs() < 1.0e-10);
        assert!((apply_easing(1.0, &Easing::EaseInOut) - 1.0).abs() < 1.0e-10);
    }

    #[test]
    fn all_easings_reach_endpoints() {
        // Boundary check: every curve must land exactly at the start
        // and end values. Animation pipelines snap to those when t
        // crosses 0 or 1; a rounding bug here produces visible jumps.
        // Back and Elastic families are listed last because they
        // overshoot in the middle but still terminate exactly at
        // endpoints by design.
        let easings = [
            Easing::Linear,
            Easing::EaseIn,
            Easing::EaseOut,
            Easing::EaseInOut,
            Easing::EaseInQuad,
            Easing::EaseOutQuad,
            Easing::EaseInOutQuad,
            Easing::EaseInCubic,
            Easing::EaseOutCubic,
            Easing::EaseInOutCubic,
            Easing::EaseInQuart,
            Easing::EaseOutQuart,
            Easing::EaseInOutQuart,
            Easing::EaseInQuint,
            Easing::EaseOutQuint,
            Easing::EaseInOutQuint,
            Easing::EaseInExpo,
            Easing::EaseOutExpo,
            Easing::EaseInOutExpo,
            Easing::EaseInCirc,
            Easing::EaseOutCirc,
            Easing::EaseInOutCirc,
            Easing::EaseInBack,
            Easing::EaseOutBack,
            Easing::EaseInOutBack,
            Easing::EaseInElastic,
            Easing::EaseOutElastic,
            Easing::EaseInOutElastic,
            Easing::EaseInBounce,
            Easing::EaseOutBounce,
            Easing::EaseInOutBounce,
        ];
        for e in &easings {
            let at_zero = apply_easing(0.0, e);
            let at_one = apply_easing(1.0, e);
            assert!(at_zero.abs() < 1.0e-10, "{:?} at 0: {}", e, at_zero);
            assert!((at_one - 1.0).abs() < 1.0e-10, "{:?} at 1: {}", e, at_one);
        }
    }

    #[test]
    fn back_family_overshoots_endpoints_in_middle() {
        // The back family exists to overshoot. Pin that property so
        // a future "fix" that clamps back into [0, 1] doesn't go
        // unnoticed.
        let near_one = apply_easing(0.95, &Easing::EaseOutBack);
        assert!(
            near_one > 1.0,
            "EaseOutBack should overshoot before settling, got {near_one}",
        );

        let near_zero = apply_easing(0.05, &Easing::EaseInBack);
        assert!(
            near_zero < 0.0,
            "EaseInBack should undershoot before pulling forward, got {near_zero}",
        );
    }

    #[test]
    fn elastic_family_oscillates_around_endpoints() {
        // The elastic family oscillates either side of the target
        // before converging. The midpoint is approximately 0.5 for
        // EaseInOutElastic but the two ease-out / ease-in curves
        // dip past 0 / overshoot 1. Pin a sample of that behavior.
        let dip = apply_easing(0.1, &Easing::EaseInElastic);
        assert!(
            dip < 0.05,
            "EaseInElastic near 0 should be very small or negative, got {dip}",
        );

        // EaseOutElastic samples a slight overshoot near t=0.1; the
        // damped oscillation means we just check it's not stuck at
        // exactly the target line.
        let early = apply_easing(0.1, &Easing::EaseOutElastic);
        assert!(
            !(early - 0.1).abs().is_finite() || (early > 0.0),
            "EaseOutElastic should produce a non-trivial intermediate, got {early}",
        );
    }

    // -----------------------------------------------------------------------
    // Cubic bezier solver
    //
    // The Newton-Raphson solver runs at most 8 iterations. The CSS
    // canonical curves are well-behaved (monotonic, x'(s) > 0 in [0,1]),
    // so 8 steps comfortably converge well within visible tolerances.
    // -----------------------------------------------------------------------

    #[test]
    fn cubic_bezier_easing_linear() {
        // A linear cubic bezier: (0.0, 0.0, 1.0, 1.0)
        let e = Easing::CubicBezier(0.0, 0.0, 1.0, 1.0);
        for i in 0..=10 {
            let t = i as f64 / 10.0;
            let result = apply_easing(t, &e);
            assert!((result - t).abs() < 0.01, "t={}: {}", t, result);
        }
    }

    #[test]
    fn cubic_bezier_endpoints_are_exact() {
        // CSS spec: bezier curves anchor exactly at (0,0) and (1,1)
        // regardless of the control points. The solver short-circuits
        // those values; a regression here produces a visible jump.
        for (x1, y1, x2, y2) in [
            (0.25_f32, 0.1, 0.25, 1.0), // CSS `ease`
            (0.42, 0.0, 1.0, 1.0),      // CSS `ease-in`
            (0.0, 0.0, 0.58, 1.0),      // CSS `ease-out`
            (0.42, 0.0, 0.58, 1.0),     // CSS `ease-in-out`
        ] {
            let e = Easing::CubicBezier(x1, y1, x2, y2);
            assert!(apply_easing(0.0, &e).abs() < 1.0e-10);
            assert!((apply_easing(1.0, &e) - 1.0).abs() < 1.0e-10);
        }
    }

    #[test]
    fn cubic_bezier_ease_curve_resembles_css_ease() {
        // CSS `ease` (the default `transition-timing-function`) is
        // bezier (0.25, 0.1, 0.25, 1.0). At t=0.5 the y is roughly
        // 0.80; pinned to a generous tolerance because the renderer
        // is interpolating positions, not chasing IEEE bit-identity.
        let e = Easing::CubicBezier(0.25, 0.1, 0.25, 1.0);
        let mid = apply_easing(0.5, &e);
        assert!(
            (mid - 0.80).abs() < 0.03,
            "css `ease` at t=0.5 should be near 0.80, got {mid}",
        );
    }

    #[test]
    fn cubic_bezier_ease_in_starts_slow_and_finishes_fast() {
        // CSS `ease-in` is (0.42, 0.0, 1.0, 1.0). The first half
        // moves substantially less than half the distance; verify
        // the slow start.
        let e = Easing::CubicBezier(0.42, 0.0, 1.0, 1.0);
        let early = apply_easing(0.25, &e);
        assert!(
            early < 0.10,
            "css `ease-in` at t=0.25 should still be near 0, got {early}",
        );
        let late = apply_easing(0.85, &e);
        assert!(
            late > 0.7,
            "css `ease-in` at t=0.85 should be approaching 1, got {late}",
        );
    }

    #[test]
    fn cubic_bezier_ease_out_starts_fast_and_finishes_slow() {
        // CSS `ease-out` is (0.0, 0.0, 0.58, 1.0); mirror of ease-in.
        // The function is concave-down, so y at t=0.25 is meaningfully
        // ahead of t=0.25 itself (the linear baseline).
        let e = Easing::CubicBezier(0.0, 0.0, 0.58, 1.0);
        let early = apply_easing(0.25, &e);
        assert!(
            early > 0.30,
            "css `ease-out` at t=0.25 should pull ahead of linear, got {early}",
        );
        let late = apply_easing(0.85, &e);
        assert!(
            late > 0.95,
            "css `ease-out` at t=0.85 should be very close to 1, got {late}",
        );
    }

    #[test]
    fn cubic_bezier_solver_handles_near_degenerate_curve() {
        // (0, 0, 0, 1) makes x'(0) = 0 (degenerate slope at the
        // start). Newton-Raphson would normally divide by zero; the
        // solver guards against that with the |dx| < 1e-7 break.
        // The result must remain finite and monotonic, even if the
        // intermediate values aren't a perfect smooth curve.
        let e = Easing::CubicBezier(0.0, 0.0, 0.0, 1.0);
        let mut last = 0.0;
        for i in 0..=10 {
            let t = i as f64 / 10.0;
            let v = apply_easing(t, &e);
            assert!(v.is_finite(), "non-finite at t={t}: {v}");
            assert!(
                v + 1.0e-9 >= last,
                "non-monotonic: at t={t} got {v} after {last}",
            );
            last = v;
        }
        // Endpoints anchor exactly.
        assert!(apply_easing(0.0, &e).abs() < 1.0e-10);
        assert!((apply_easing(1.0, &e) - 1.0).abs() < 1.0e-10);
    }

    // -- Timed advance tests -------------------------------------------------

    #[test]
    fn advance_uses_easing() {
        let mut tween = Tween::new(0.0, 100.0, 1000).easing(Easing::EaseInQuad);
        tween.start(0);
        tween.advance(500);
        // EaseInQuad at t=0.5: 0.25, so value should be ~25
        let v = tween.value().unwrap();
        assert!((v - 25.0).abs() < 0.01, "got: {}", v);
    }

    #[test]
    fn repeat_restarts() {
        let mut tween = Tween::new(0.0, 100.0, 100).easing(Easing::Linear).repeat(2);
        tween.start(0);
        tween.advance(100); // first cycle ends
        assert!(!tween.finished());
        assert_eq!(tween.repeat, Some(Repeat::Times(1)));
        tween.advance(200); // second cycle ends
        assert!(tween.finished());
    }

    #[test]
    fn auto_reverse_swaps_direction() {
        let mut tween = Tween::new(0.0, 100.0, 100)
            .easing(Easing::Linear)
            .repeat_forever()
            .auto_reverse(true);
        tween.start(0);
        tween.advance(100); // first cycle ends, should reverse
        assert_eq!(tween.from, 100.0);
        assert_eq!(tween.to, 0.0);
        tween.advance(150); // halfway through reverse
        let v = tween.value().unwrap();
        assert!((v - 50.0).abs() < 1.0, "got: {}", v);
    }

    // -- Spring tests --------------------------------------------------------

    #[test]
    fn spring_config_presets() {
        let gentle = SpringConfig::gentle();
        assert_eq!(gentle.stiffness, 120.0);
        assert_eq!(gentle.damping, 14.0);

        let bouncy = SpringConfig::bouncy();
        assert_eq!(bouncy.stiffness, 300.0);
        assert_eq!(bouncy.damping, 10.0);

        let stiff = SpringConfig::stiff();
        assert_eq!(stiff.stiffness, 400.0);
        assert_eq!(stiff.damping, 30.0);

        let snappy = SpringConfig::snappy();
        assert_eq!(snappy.stiffness, 200.0);
        assert_eq!(snappy.damping, 20.0);

        let molasses = SpringConfig::molasses();
        assert_eq!(molasses.stiffness, 60.0);
        assert_eq!(molasses.damping, 12.0);
    }

    #[test]
    fn spring_config_builder() {
        let config = SpringConfig::default()
            .stiffness(250.0)
            .damping(18.0)
            .mass(2.0)
            .initial_velocity(5.0);
        assert_eq!(config.stiffness, 250.0);
        assert_eq!(config.damping, 18.0);
        assert_eq!(config.mass, 2.0);
        assert_eq!(config.initial_velocity, 5.0);
    }

    #[test]
    fn spring_approaches_target() {
        let mut tween = Tween::spring(0.0, 100.0, SpringConfig::default());
        tween.start(0);

        tween.advance(100);
        let v = tween.value().unwrap();
        assert!(v > 0.0, "spring should move toward target, got: {}", v);
        assert!(
            v < 100.0,
            "spring shouldn't overshoot this early with default damping"
        );
        assert!(!tween.finished());
    }

    #[test]
    fn spring_settles_at_target() {
        let mut tween = Tween::spring(0.0, 100.0, SpringConfig::stiff());
        tween.start(0);

        // Advance enough for the spring to settle
        for t in (100..=5000).step_by(100) {
            tween.advance(t);
            if tween.finished() {
                break;
            }
        }

        assert!(tween.finished(), "stiff spring should settle within 5s");
        assert!(
            (tween.value().unwrap() - 100.0).abs() < 0.01,
            "settled value should be at target"
        );
    }

    #[test]
    fn bouncy_spring_overshoots() {
        let mut tween = Tween::spring(0.0, 100.0, SpringConfig::bouncy());
        tween.start(0);

        let mut max_value: f64 = 0.0;
        for t in (1..=2000).step_by(1) {
            tween.advance(t);
            if let Some(v) = tween.value() {
                max_value = max_value.max(v);
            }
        }

        assert!(
            max_value > 100.0,
            "bouncy spring should overshoot target, max was: {}",
            max_value
        );
    }

    #[test]
    fn spring_with_initial_velocity() {
        let config = SpringConfig::default().initial_velocity(50.0);
        let mut tween = Tween::spring(0.0, 100.0, config);
        tween.start(0);

        tween.advance(50);
        let with_velocity = tween.value().unwrap();

        let mut tween2 = Tween::spring(0.0, 100.0, SpringConfig::default());
        tween2.start(0);
        tween2.advance(50);
        let without_velocity = tween2.value().unwrap();

        assert!(
            with_velocity > without_velocity,
            "initial velocity should make the spring move faster: {} vs {}",
            with_velocity,
            without_velocity
        );
    }

    #[test]
    #[should_panic(expected = "spring mass must be a positive finite number")]
    fn spring_rejects_zero_mass() {
        let _ = Tween::spring(0.0, 100.0, SpringConfig::default().mass(0.0));
    }

    #[test]
    #[should_panic(expected = "spring mass must be a positive finite number")]
    fn spring_rejects_negative_mass() {
        let _ = Tween::spring(0.0, 100.0, SpringConfig::default().mass(-1.0));
    }

    #[test]
    #[should_panic(expected = "spring mass must be a positive finite number")]
    fn spring_rejects_infinite_mass() {
        let _ = Tween::spring(0.0, 100.0, SpringConfig::default().mass(f64::INFINITY));
    }

    #[test]
    #[should_panic(expected = "spring mass must be a positive finite number")]
    fn spring_rejects_nan_mass() {
        let _ = Tween::spring(0.0, 100.0, SpringConfig::default().mass(f64::NAN));
    }

    #[test]
    fn spring_is_spring() {
        let tween = Tween::spring(0.0, 100.0, SpringConfig::default());
        assert!(tween.is_spring());

        let tween2 = Tween::new(0.0, 100.0, 500);
        assert!(!tween2.is_spring());
    }

    // -- Redirect tests ------------------------------------------------------

    #[test]
    fn redirect_changes_target() {
        let mut tween = Tween::new(0.0, 100.0, 1000).easing(Easing::Linear);
        tween.start(0);
        tween.advance(500);
        let mid = tween.value().unwrap();

        tween.redirect(50.0, 500);
        assert_eq!(tween.from, mid);
        assert_eq!(tween.to, 50.0);
        assert!(tween.running());
    }

    #[test]
    fn redirect_with_easing_override() {
        let mut tween = Tween::new(0.0, 100.0, 1000).easing(Easing::Linear);
        tween.start(0);
        tween.advance(500);

        tween.redirect_with(
            200.0,
            500,
            RedirectOpts::default()
                .easing(Easing::EaseInQuad)
                .duration(2000),
        );

        // After redirect, advance halfway through new duration
        tween.advance(1500);
        let v = tween.value().unwrap();
        // EaseInQuad at t=0.5: 0.25. Range is 50..200 (from mid to 200), so
        // value should be ~50 + 0.25 * 150 = ~87.5
        assert!((v - 87.5).abs() < 1.0, "got: {}", v);
    }

    #[test]
    fn spring_redirect_preserves_velocity() {
        let mut tween = Tween::spring(0.0, 100.0, SpringConfig::stiff());
        tween.start(0);

        // Let the spring build up velocity
        tween.advance(50);
        let value_before = tween.value().unwrap();
        assert!(value_before > 0.0);

        // Redirect to a different target
        tween.redirect(200.0, 50);
        assert_eq!(tween.from, value_before);
        assert_eq!(tween.to, 200.0);

        // The spring should continue moving (velocity preserved)
        tween.advance(51);
        let value_after = tween.value().unwrap();
        assert!(
            value_after > value_before,
            "spring should keep moving after redirect: {} vs {}",
            value_after,
            value_before
        );
    }

    #[test]
    fn spring_large_time_delta_is_capped() {
        // With the 1000-step cap, a huge time delta should not loop
        // for millions of iterations. The value should still be finite
        // and reasonable (not NaN or infinity).
        let mut tween = Tween::spring(0.0, 100.0, SpringConfig::stiff());
        tween.start(0);
        tween.advance(1_000_000); // 1 million ms, but capped to 1000 steps
        let v = tween.value().unwrap();
        assert!(
            v.is_finite(),
            "value should be finite after large delta: {}",
            v
        );
    }

    #[test]
    fn spring_overflow_stops_with_finite_value() {
        let config = SpringConfig::default()
            .stiffness(f64::MAX)
            .damping(0.0)
            .mass(f64::MIN_POSITIVE);
        let mut tween = Tween::spring(0.0, 100.0, config);
        tween.start(0);
        tween.advance(1);

        assert!(tween.finished());
        assert_eq!(tween.value(), Some(100.0));
    }
}