gpui-base 0.9.1

Behavior, interaction, and infrastructure foundations for GPUI applications.
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
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
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
#[cfg(not(target_family = "wasm"))]
use std::time::Instant;
use std::{cell::RefCell, rc::Rc, time::Duration};
#[cfg(target_family = "wasm")]
use web_time::Instant;

use gpui::{
    App, Bounds, ElementId, Pixels, SharedString, Size, SpringConfig, SpringState, SpringTarget,
    Window,
};

use crate::animation::{Lerp, ease_out_cubic};

mod easing;
mod keyframes;
mod presence;
mod reveal;
mod sequence;
mod stagger;
mod timing;

pub use easing::{Easing, EasingError, LinearStop, StepPosition};
pub use keyframes::{Discrete, DiscreteError, Keyframe, KeyframeError, Keyframes};
pub use presence::{Presence, PresencePhase, PresenceSample};
pub use reveal::MotionReveal;
pub use sequence::{Sequence, SequenceSample, SequenceStep};
pub use stagger::{Stagger, StaggerOrigin};
pub use timing::{
    IterationCount, MotionPhase, PlaybackDirection, SignedDuration, Timing, TimingSample,
};

/// Matches GPUI's own default spring settling tolerance.
const DEFAULT_SPRING_EPSILON: f32 = 0.001;

/// A value that can be interpolated between two application-owned targets.
pub trait Interpolate: Clone {
    fn interpolate(&self, target: &Self, progress: f32) -> Self;
}

impl<T: Lerp> Interpolate for T {
    fn interpolate(&self, target: &Self, progress: f32) -> Self {
        self.lerp(target, progress)
    }
}

impl Interpolate for Size<Pixels> {
    fn interpolate(&self, target: &Self, progress: f32) -> Self {
        Size::new(
            self.width.lerp(&target.width, progress),
            self.height.lerp(&target.height, progress),
        )
    }
}

impl Interpolate for Bounds<Pixels> {
    fn interpolate(&self, target: &Self, progress: f32) -> Self {
        Bounds::new(
            self.origin.lerp(&target.origin, progress),
            self.size.interpolate(&target.size, progress),
        )
    }
}

/// A presentation-neutral bundle for coordinated paint transforms.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MotionTransform {
    pub translation: gpui::Point<Pixels>,
    pub scale: gpui::Point<f32>,
    pub rotation_radians: f32,
    pub opacity: f32,
}

impl MotionTransform {
    pub fn identity() -> Self {
        Self {
            translation: gpui::point(gpui::px(0.0), gpui::px(0.0)),
            scale: gpui::point(1.0, 1.0),
            rotation_radians: 0.0,
            opacity: 1.0,
        }
    }
}

impl Default for MotionTransform {
    fn default() -> Self {
        Self::identity()
    }
}

impl Interpolate for MotionTransform {
    fn interpolate(&self, target: &Self, progress: f32) -> Self {
        Self {
            translation: self.translation.lerp(&target.translation, progress),
            scale: gpui::point(
                self.scale.x.lerp(&target.scale.x, progress),
                self.scale.y.lerp(&target.scale.y, progress),
            ),
            rotation_radians: self
                .rotation_radians
                .lerp(&target.rotation_radians, progress),
            opacity: self.opacity.lerp(&target.opacity, progress),
        }
    }
}

/// How a value transition responds to the application's reduced-motion setting.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum ReducedMotion {
    /// Adopt the target immediately. Appropriate for spatial motion.
    #[default]
    Finish,
    /// Keep the transition timing, for non-spatial effects such as fades.
    Continue,
}

/// CSS-like timing policy for a target-value transition.
///
/// This type is intentionally separate from [`crate::animation::Transition`],
/// whose legacy interface applies concrete fade, slide, and size effects to an
/// element. A value transition never chooses a visual property for the caller.
#[derive(Clone)]
pub struct Transition {
    duration: Duration,
    delay: SignedDuration,
    easing: Easing,
    reduced_motion: ReducedMotion,
}

impl Transition {
    pub fn new(duration: Duration) -> Self {
        Self {
            duration,
            delay: SignedDuration::ZERO,
            easing: Easing::Custom(Rc::new(ease_out_cubic)),
            reduced_motion: ReducedMotion::Finish,
        }
    }

    /// Select reduced-motion behavior for this transition only.
    /// The application's preference and other motion channels are unchanged.
    ///
    /// [`transition`], [`transition_with_status`] and
    /// [`TransitionState::sample`] read it. [`Presence`] still finishes at
    /// once under reduced motion.
    pub fn reduced_motion(mut self, behavior: ReducedMotion) -> Self {
        self.reduced_motion = behavior;
        self
    }

    pub fn delay(mut self, delay: impl Into<SignedDuration>) -> Self {
        self.delay = delay.into();
        self
    }

    pub fn ease(mut self, easing: impl Fn(f32) -> f32 + 'static) -> Self {
        self.easing = Easing::Custom(Rc::new(easing));
        self
    }

    pub fn easing(mut self, easing: Easing) -> Self {
        self.easing = easing;
        self
    }

    fn sample(&self, progress: f32) -> f32 {
        self.easing.sample(progress)
    }

    /// The easing curve, for a caller that samples one timeline at several
    /// offsets, such as a staggered plot appear.
    pub(crate) fn curve(&self) -> &Easing {
        &self.easing
    }

    fn progress(&self, elapsed: Duration, duration: Duration) -> (f32, MotionStatus) {
        let Some(active_elapsed) = self.delay.active_elapsed(elapsed) else {
            return (0.0, MotionStatus::Delayed);
        };
        if duration.is_zero() || active_elapsed >= duration {
            return (1.0, MotionStatus::Finished);
        }
        (
            active_elapsed.as_secs_f32() / duration.as_secs_f32(),
            MotionStatus::Running,
        )
    }

    /// The elapsed time at which [`Self::progress`] over the transition's own
    /// duration first reports `Finished`.
    fn finishes_after(&self) -> Duration {
        match self.delay {
            SignedDuration::Positive(delay) => delay.saturating_add(self.duration),
            SignedDuration::Negative(delay) => self.duration.saturating_sub(delay),
        }
    }
}

impl From<Duration> for SignedDuration {
    fn from(duration: Duration) -> Self {
        Self::positive(duration)
    }
}

/// Identifies one independently transitioning value.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct TransitionId(ElementId);

impl From<ElementId> for TransitionId {
    fn from(id: ElementId) -> Self {
        Self(id)
    }
}

impl From<&'static str> for TransitionId {
    fn from(id: &'static str) -> Self {
        Self(id.into())
    }
}

impl From<String> for TransitionId {
    fn from(id: String) -> Self {
        Self(id.into())
    }
}

impl From<SharedString> for TransitionId {
    fn from(id: SharedString) -> Self {
        Self(id.into())
    }
}

impl From<usize> for TransitionId {
    fn from(id: usize) -> Self {
        Self(id.into())
    }
}

impl From<i32> for TransitionId {
    fn from(id: i32) -> Self {
        Self(id.into())
    }
}

impl From<TransitionId> for ElementId {
    fn from(id: TransitionId) -> Self {
        ElementId::NamedChild(id.0.into(), "__base-transition-state".into())
    }
}

impl<I, C> From<(I, C)> for TransitionId
where
    I: Into<ElementId>,
    C: Into<SharedString>,
{
    fn from((id, channel): (I, C)) -> Self {
        Self(ElementId::NamedChild(id.into().into(), channel.into()))
    }
}

#[derive(Clone)]
struct ValueTransition<T> {
    from: T,
    /// Where the running transition logically started, before any reversal
    /// shortened it: what a CSS transition calls its reversing-adjusted start.
    reversing_adjusted_start: T,
    /// The policy the running transition started with, kept until it is
    /// retargeted.
    policy: Transition,
    target: T,
    started_at: Instant,
    reversing_factor: f32,
    duration: Duration,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MotionStatus {
    Idle,
    Delayed,
    Running,
    Finished,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MotionValue<T> {
    pub value: T,
    pub status: MotionStatus,
}

/// Caller-owned state for one target-value transition, independent of mounting.
///
/// Keyed state lives only while its element renders, so a virtualized row that
/// scrolls out and back restarts at its target. Keep a `TransitionState` with the
/// row's data instead and sample it while rendering:
///
/// ```ignore
/// let opacity = row.highlight.sample(target, policy, window, cx).value;
/// ```
///
/// Clones share its clock and interruption/reversal history. The first sample
/// adopts its target immediately; later samples use the same algorithm as
/// [`transition_with_status`]. No view or window is retained. A new handle
/// resets it.
#[derive(Clone)]
pub struct TransitionState<T> {
    state: Rc<RefCell<Option<ValueTransition<T>>>>,
}

impl<T> Default for TransitionState<T> {
    fn default() -> Self {
        Self {
            state: Rc::new(RefCell::new(None)),
        }
    }
}

impl<T: Interpolate + PartialEq + 'static> TransitionState<T> {
    /// Returns the current value toward `target`, as [`transition_with_status`]
    /// does, and requests the next animation frame while the status is
    /// `Delayed` or `Running`.
    ///
    /// Call this while rendering an element. A target that changes while the
    /// element is not rendered starts transitioning at the next sample.
    pub fn sample(
        &self,
        target: T,
        policy: Transition,
        window: &mut Window,
        cx: &mut App,
    ) -> MotionValue<T> {
        let now = cx.background_executor().now();
        let mut state = self.state.borrow_mut();
        let state = state.get_or_insert_with(|| ValueTransition {
            from: target.clone(),
            reversing_adjusted_start: target.clone(),
            policy: policy.clone(),
            target: target.clone(),
            started_at: now,
            reversing_factor: 1.0,
            duration: policy.duration,
        });
        let snapshot = state.clone();
        let sampled = sample_transition(
            &snapshot,
            target,
            policy,
            now,
            cx.reduce_motion(),
            |update| update(state),
        );
        if matches!(
            sampled.status,
            MotionStatus::Delayed | MotionStatus::Running
        ) {
            window.request_animation_frame();
        }
        sampled
    }
}

/// Returns the current value for a CSS-like transition toward `target`.
///
/// State is keyed by `id`. The first value is adopted immediately; later target
/// changes transition from the value sampled at that instant. Components opt
/// into this function explicitly—base components do not install default motion.
///
/// Call this while rendering an element, where GPUI keyed element state is
/// available. A channel id must identify one value type within that element.
pub fn transition<T>(
    id: impl Into<TransitionId>,
    target: T,
    policy: Transition,
    window: &mut Window,
    cx: &mut App,
) -> T
where
    T: Interpolate + PartialEq + 'static,
{
    transition_with_status(id, target, policy, window, cx).value
}

pub fn transition_with_status<T>(
    id: impl Into<TransitionId>,
    target: T,
    policy: Transition,
    window: &mut Window,
    cx: &mut App,
) -> MotionValue<T>
where
    T: Interpolate + PartialEq + 'static,
{
    let id: ElementId = id.into().into();
    let now = cx.background_executor().now();
    let state = window.use_keyed_state(id, cx, |_, _| ValueTransition {
        from: target.clone(),
        reversing_adjusted_start: target.clone(),
        policy: policy.clone(),
        target: target.clone(),
        started_at: now,
        reversing_factor: 1.0,
        duration: policy.duration,
    });

    let snapshot = state.read(cx).clone();
    let reduced = cx.reduce_motion();
    let sampled = sample_transition(&snapshot, target, policy, now, reduced, |update| {
        state.update(cx, |state, _| update(state));
    });
    if matches!(
        sampled.status,
        MotionStatus::Delayed | MotionStatus::Running
    ) {
        window.request_animation_frame();
    }
    sampled
}

fn sample_transition<T>(
    snapshot: &ValueTransition<T>,
    target: T,
    policy: Transition,
    now: Instant,
    reduced_motion: bool,
    mut update: impl FnMut(&mut dyn FnMut(&mut ValueTransition<T>)),
) -> MotionValue<T>
where
    T: Interpolate + PartialEq + 'static,
{
    if (reduced_motion && policy.reduced_motion == ReducedMotion::Finish)
        || policy.duration.is_zero()
    {
        if snapshot.from != target || snapshot.target != target {
            update(&mut |state| {
                state.from = target.clone();
                state.reversing_adjusted_start = target.clone();
                state.policy = policy.clone();
                state.target = target.clone();
                state.started_at = now;
                state.reversing_factor = 1.0;
                state.duration = policy.duration;
            });
        }
        return MotionValue {
            value: target,
            status: MotionStatus::Finished,
        };
    }

    let elapsed = now.saturating_duration_since(snapshot.started_at);
    let (progress, status) = snapshot.policy.progress(elapsed, snapshot.duration);
    let sampled = snapshot
        .from
        .interpolate(&snapshot.target, snapshot.policy.sample(progress));

    let (value, status) = if snapshot.target != target {
        // As CSS transitions do: only a running transition sent back to where
        // it logically started is a reversal.
        let reversing = matches!(status, MotionStatus::Running | MotionStatus::Delayed)
            && target == snapshot.reversing_adjusted_start;
        let reversing_factor = if reversing {
            (snapshot.policy.sample(progress) * snapshot.reversing_factor
                + (1.0 - snapshot.reversing_factor))
                .abs()
                .clamp(0.0, 1.0)
        } else {
            1.0
        };
        let duration = policy.duration.mul_f64(f64::from(reversing_factor));
        // A reversal shortens a negative delay by the same factor.
        let mut active_policy = policy.clone();
        if reversing && let SignedDuration::Negative(delay) = policy.delay {
            active_policy.delay =
                SignedDuration::negative(delay.mul_f64(f64::from(reversing_factor)));
        }
        update(&mut |state| {
            state.reversing_adjusted_start = if reversing {
                snapshot.target.clone()
            } else {
                sampled.clone()
            };
            state.policy = active_policy.clone();
            state.from = sampled.clone();
            state.target = target.clone();
            state.started_at = now;
            state.reversing_factor = reversing_factor;
            state.duration = duration;
        });
        let (initial_progress, initial_status) = active_policy.progress(Duration::ZERO, duration);
        (
            sampled.interpolate(&target, active_policy.sample(initial_progress)),
            initial_status,
        )
    } else {
        (
            sampled,
            if snapshot.from == snapshot.target {
                MotionStatus::Idle
            } else {
                status
            },
        )
    };
    MotionValue { value, status }
}

#[derive(Clone, Copy)]
struct KeyframePlayback {
    started_at: Instant,
}

/// Samples a keyed keyframe playback and requests frames while it is active.
///
/// The stable `id` owns the playback's start time. Re-rendering with the same
/// ID continues that playback; it does not restart when `keyframes` or `timing`
/// is reconstructed. To replay a sequence, include an application-owned
/// generation in the ID, for example `("notification-enter", generation)`.
pub fn animate_keyframes<T>(
    id: impl Into<TransitionId>,
    keyframes: &Keyframes<T>,
    timing: Timing,
    window: &mut Window,
    cx: &mut App,
) -> MotionValue<T>
where
    T: Interpolate + 'static,
{
    let id: TransitionId = id.into();
    let id = ElementId::NamedChild(ElementId::from(id).into(), "__keyframes".into());
    let now = cx.background_executor().now();
    let state = window.use_keyed_state(id, cx, |_, _| KeyframePlayback { started_at: now });
    let started_at = state.read(cx).started_at;

    if cx.reduce_motion() {
        return MotionValue {
            value: keyframes.sample(1.0),
            status: MotionStatus::Finished,
        };
    }

    let sample = timing.sample(now.saturating_duration_since(started_at));
    let status = match sample.phase {
        MotionPhase::Before => MotionStatus::Delayed,
        MotionPhase::Active => MotionStatus::Running,
        MotionPhase::After => MotionStatus::Finished,
    };
    if matches!(status, MotionStatus::Delayed | MotionStatus::Running) {
        window.request_animation_frame();
    }
    MotionValue {
        value: keyframes.sample(sample.directed_progress),
        status,
    }
}

/// A physical spring policy for [`spring`].
///
/// A spring is the counterpart to [`Transition`] for values that can be
/// retargeted while they are still moving. A duration-based transition restarts
/// its easing from the value sampled at that instant, which is continuous in
/// position but not in velocity. A spring carries velocity across the retarget,
/// so a value reversed mid-flight decelerates and turns around instead of
/// snapping to a new curve's initial speed.
#[derive(Clone, Copy, Debug)]
pub struct Spring {
    response: Duration,
    damping: f32,
    epsilon: f32,
    travel: bool,
}

/// Invalid physical or settling parameters for a [`Spring`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SpringError {
    InvalidDamping,
    InvalidEpsilon,
}

impl std::fmt::Display for SpringError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidDamping => f.write_str("spring damping must be finite and non-negative"),
            Self::InvalidEpsilon => {
                f.write_str("spring epsilon must be finite and greater than zero")
            }
        }
    }
}

impl std::error::Error for SpringError {}

impl Spring {
    /// Builds a spring that reaches its target in about `response` without
    /// overshooting it.
    ///
    /// `response` is not a duration in the sense [`Transition::new`] means one.
    /// A spring has no end to schedule: this is the period one full oscillation
    /// would take without damping, which is the scale the motion is felt at
    /// rather than the moment it stops. The remaining fraction of a percent
    /// keeps settling past it, until it is within the tolerance
    /// [`Self::with_epsilon`] sets.
    ///
    /// A zero response adopts the target on the spot, as a zero duration does
    /// for a transition. Say that with [`Self::with_travel`] where it is what
    /// you mean; a zero here is the degenerate case, defined so an infinitely
    /// stiff spring resolves rather than dividing by its own period.
    pub const fn new(response: Duration) -> Self {
        Self {
            response,
            damping: 1.0,
            epsilon: DEFAULT_SPRING_EPSILON,
            travel: true,
        }
    }

    /// Sets the damping ratio, which is `1.0` — no overshoot — by default.
    ///
    /// Below `1.0` the spring passes its target and comes back; above `1.0` it
    /// approaches slowly. Overshoot suits a value with room to pass its target
    /// and nothing to collide with. A height, an opacity, or anything bounded by
    /// the geometry around it should stay at the default.
    ///
    /// This is $\zeta$, not GPUI's `SpringConfig::damping`, which is the
    /// coefficient $c = 2 \zeta \omega_0$.
    ///
    /// # Panics
    ///
    /// Panics when `ratio` is negative or non-finite. Use
    /// [`Self::try_with_damping`] when the value is not a trusted constant.
    pub const fn with_damping(self, ratio: f32) -> Self {
        match self.try_with_damping(ratio) {
            Ok(spring) => spring,
            Err(_) => panic!("spring damping must be finite and non-negative"),
        }
    }

    /// Checked form of [`Self::with_damping`].
    pub const fn try_with_damping(mut self, ratio: f32) -> Result<Self, SpringError> {
        if !ratio.is_finite() || ratio < 0.0 {
            return Err(SpringError::InvalidDamping);
        }
        self.damping = ratio;
        Ok(self)
    }

    /// Sets whether the spring travels to its target or adopts it on the spot.
    ///
    /// A value the pointer is already moving — a panel being dragged by its
    /// resize handle — must not lag behind the pointer, so the spring stops
    /// travelling for as long as the drag lasts. Retained state stays pinned to
    /// the target meanwhile, so travel resumes from the value the drag released
    /// rather than from wherever the spring was when it began.
    ///
    /// This says at the call that the motion is suspended, and it says it
    /// without disturbing the response, damping or tolerance the spring is
    /// configured with — which a policy swapped out for the length of the drag
    /// would have to restate or discard.
    pub const fn with_travel(mut self, travel: bool) -> Self {
        self.travel = travel;
        self
    }

    /// Sets the settling tolerance, expressed in the target's own units.
    ///
    /// The default suits targets that move within a normalized `0..1` range. A
    /// spring over pixels settles perceptibly sooner with a coarser tolerance,
    /// which also ends the animation frames that the remaining sub-pixel motion
    /// would otherwise request.
    ///
    /// # Panics
    ///
    /// Panics when `epsilon` is zero, negative, or non-finite. Use
    /// [`Self::try_with_epsilon`] when the value is not a trusted constant.
    pub const fn with_epsilon(self, epsilon: f32) -> Self {
        match self.try_with_epsilon(epsilon) {
            Ok(spring) => spring,
            Err(_) => panic!("spring epsilon must be finite and greater than zero"),
        }
    }

    /// Checked form of [`Self::with_epsilon`].
    pub const fn try_with_epsilon(mut self, epsilon: f32) -> Result<Self, SpringError> {
        if !epsilon.is_finite() || epsilon <= 0.0 {
            return Err(SpringError::InvalidEpsilon);
        }
        self.epsilon = epsilon;
        Ok(self)
    }

    /// Returns the settling tolerance in the target's own units.
    pub const fn epsilon(self) -> f32 {
        self.epsilon
    }

    /// The physical parameters GPUI integrates. The response must be non-zero;
    /// [`spring`] adopts the target before reaching here when it is not.
    ///
    /// Derived on use rather than stored, so the builders stay `const`: neither
    /// `Duration::as_secs_f32` nor the square root that recovers a damping ratio
    /// from a built config can be called from a `const fn`.
    fn config(&self) -> SpringConfig {
        let frequency = std::f32::consts::TAU / self.response.as_secs_f32();
        SpringConfig::new(frequency * frequency, 2.0 * self.damping * frequency, 1.0)
    }
}

#[derive(Clone, Copy)]
struct SpringTransition {
    state: SpringState,
    target: f32,
    updated_at: Instant,
}

/// Returns the current value for a spring travelling toward `target`.
///
/// State is keyed by `id` exactly as [`transition`] keys its own. The first
/// value is adopted immediately; later target changes preserve both the current
/// position and the current velocity, so an interrupted spring is redirected
/// rather than restarted.
///
/// Call this while rendering an element, where GPUI keyed element state is
/// available. A channel id must identify one value within that element.
pub fn spring<T>(
    id: impl Into<TransitionId>,
    target: T,
    policy: Spring,
    window: &mut Window,
    cx: &mut App,
) -> T::Output
where
    T: SpringTarget,
{
    let id: ElementId = id.into().into();
    let now = cx.background_executor().now();
    let target_position = target.target();
    let state = window.use_keyed_state(id, cx, |_, _| SpringTransition {
        state: SpringState {
            position: target_position,
            velocity: 0.0,
        },
        target: target_position,
        updated_at: now,
    });

    let snapshot = *state.read(cx);
    let at_rest_on_target =
        snapshot.state.position == target_position && snapshot.state.velocity == 0.0;

    // The overwhelmingly common case: a spring nothing is currently moving. It
    // has no state to advance and no frame to ask for, so it never builds a
    // config or steps one — a settled spring costs a read and two comparisons.
    // Every branch below would return this same value and write nothing.
    //
    // Resting writes nothing, so `updated_at` goes stale for as long as the rest
    // lasts. The next retarget then steps a zero displacement at zero velocity
    // over that whole gap, which any elapsed time leaves where it is, so the
    // stale clock cannot move the value — it only has to not produce a NaN, and
    // every term the propagator scales is finite.
    if at_rest_on_target {
        return target.resolve(target_position);
    }

    let settle = |state: &mut SpringTransition| {
        state.state = SpringState {
            position: target_position,
            velocity: 0.0,
        };
        state.target = target_position;
        state.updated_at = now;
    };

    if cx.reduce_motion() || !policy.travel || policy.response.is_zero() {
        state.update(cx, |state, _| settle(state));
        return target.resolve(target_position);
    }

    // Advance over the frame that just elapsed, which the previous target
    // governed, before adopting the new one for the frame to come.
    let elapsed = now
        .saturating_duration_since(snapshot.updated_at)
        .as_secs_f32();
    let config = policy.config();
    let stepped = config.step(snapshot.state, snapshot.target, elapsed);

    if config.is_settled(stepped, target_position, policy.epsilon) {
        state.update(cx, |state, _| settle(state));
        return target.resolve(target_position);
    }

    state.update(cx, |state, _| {
        state.state = stepped;
        state.target = target_position;
        state.updated_at = now;
    });
    window.request_animation_frame();
    target.resolve(stepped.position)
}

#[cfg(test)]
mod css_timing_tests {
    use super::{
        Easing, IterationCount, LinearStop, MotionPhase, PlaybackDirection, SignedDuration,
        StepPosition, Timing,
    };
    use std::{num::NonZeroU32, sync::Arc, time::Duration};

    #[test]
    fn css_keyword_easing_matches_published_reference_samples() {
        for (easing, samples) in [
            (Easing::Ease, [(0.2, 0.295), (0.5, 0.802), (0.8, 0.976)]),
            (Easing::EaseIn, [(0.2, 0.062), (0.5, 0.315), (0.8, 0.692)]),
            (Easing::EaseOut, [(0.2, 0.308), (0.5, 0.685), (0.8, 0.938)]),
            (Easing::EaseInOut, [(0.2, 0.082), (0.5, 0.5), (0.8, 0.918)]),
        ] {
            for (progress, expected) in samples {
                let actual = easing.sample(progress);
                assert!(
                    (actual - expected).abs() < 0.002,
                    "{easing:?}({progress}) = {actual}, expected {expected}"
                );
            }
        }
    }

    #[test]
    fn cubic_bezier_easing_keeps_anticipation_and_overshoot() {
        let anticipate = Easing::cubic_bezier(1.0, -0.4, 0.35, 0.95).unwrap();
        let overshoot = Easing::cubic_bezier(0.175, 0.885, 0.32, 1.275).unwrap();

        assert!(anticipate.sample(0.2) < 0.0);
        assert!(overshoot.sample(0.8) > 1.0);
        for easing in [anticipate, overshoot] {
            assert_eq!(easing.sample(-1.0), 0.0);
            assert_eq!(easing.sample(2.0), 1.0);
        }
    }

    #[test]
    fn step_easing_observes_css_jump_positions() {
        let start = Easing::steps(4, StepPosition::JumpStart).unwrap();
        let end = Easing::steps(4, StepPosition::JumpEnd).unwrap();

        assert_eq!(start.sample(0.0), 0.25);
        assert_eq!(start.sample(0.24), 0.25);
        assert_eq!(start.sample(0.25), 0.5);
        assert_eq!(end.sample(0.0), 0.0);
        assert_eq!(end.sample(0.24), 0.0);
        assert_eq!(end.sample(0.25), 0.25);
        assert!(Easing::steps(0, StepPosition::JumpEnd).is_err());

        let none = Easing::steps(4, StepPosition::JumpNone).unwrap();
        let both = Easing::steps(4, StepPosition::JumpBoth).unwrap();
        assert_eq!(none.sample(0.0), 0.0);
        assert!((none.sample(0.5) - 2.0 / 3.0).abs() < f32::EPSILON);
        assert_eq!(none.sample(1.0), 1.0);
        assert_eq!(both.sample(0.0), 0.2);
        assert_eq!(both.sample(1.0), 1.0);
        assert!(Easing::steps(1, StepPosition::JumpNone).is_err());
    }

    #[test]
    fn linear_stops_fill_omitted_positions_before_sampling() {
        let easing = Easing::linear_stops([
            LinearStop::at(0.0, 0.0),
            LinearStop::new(0.2),
            LinearStop::new(0.8),
            LinearStop::at(1.0, 1.0),
        ])
        .unwrap();

        assert!((easing.sample(1.0 / 3.0) - 0.2).abs() < 1e-6);
        assert!((easing.sample(0.5) - 0.5).abs() < 1e-6);
        assert!(
            Easing::linear_stops([LinearStop::at(0.0, 0.8), LinearStop::at(1.0, 0.2)]).is_err()
        );
    }

    #[test]
    fn curves_built_without_stops_or_jumps_sample_linearly() {
        // Both are rejected by the constructors, but the variants are public.
        let no_stops = Easing::LinearStops(Arc::from([]));
        let no_jumps = Easing::Steps {
            count: NonZeroU32::MIN,
            position: StepPosition::JumpNone,
        };

        for (progress, expected) in [(-1.0, 0.0), (0.25, 0.25), (2.0, 1.0)] {
            assert_eq!(
                no_stops.sample(progress),
                expected,
                "no stops at {progress}"
            );
            assert_eq!(
                no_jumps.sample(progress),
                expected,
                "no jumps at {progress}"
            );
        }
    }

    #[test]
    fn negative_delay_starts_inside_the_active_interval() {
        let timing = Timing::new(Duration::from_millis(100))
            .delay(SignedDuration::negative(Duration::from_millis(25)));
        let sample = timing.sample(Duration::ZERO);

        assert_eq!(sample.phase, MotionPhase::Active);
        assert!((sample.directed_progress - 0.25).abs() < f32::EPSILON);
        assert!(sample.active);
        assert!(!sample.finished);
    }

    #[test]
    fn alternate_direction_reverses_odd_iterations() {
        let timing = Timing::new(Duration::from_millis(100))
            .iterations(IterationCount::Finite(2))
            .direction(PlaybackDirection::Alternate)
            .ease(Easing::Linear);

        let first = timing.sample(Duration::from_millis(25));
        let second = timing.sample(Duration::from_millis(125));
        let finished = timing.sample(Duration::from_millis(200));

        assert_eq!(first.iteration, 0);
        assert_eq!(first.directed_progress, 0.25);
        assert_eq!(second.iteration, 1);
        assert_eq!(second.directed_progress, 0.75);
        assert_eq!(finished.phase, MotionPhase::After);
        assert_eq!(finished.directed_progress, 0.0);
        assert!(finished.finished);
    }
}

#[cfg(test)]
mod motion_track_tests {
    use super::{
        Discrete, Easing, Interpolate as _, Keyframe, KeyframeError, Keyframes, MotionTransform,
        Stagger, StaggerOrigin,
    };
    use gpui::{Bounds, Point, Size, point, px, size};
    use std::time::Duration;

    #[test]
    fn keyframes_validate_offsets_and_sample_each_segments_easing() {
        assert!(matches!(
            Keyframes::try_new([Keyframe::new(0.2, 0.0_f32), Keyframe::new(1.0, 1.0_f32),]),
            Err(KeyframeError::MissingEndpoint)
        ));
        assert!(matches!(
            Keyframes::try_new([
                Keyframe::new(0.0, 0.0_f32),
                Keyframe::new(0.8, 1.0_f32),
                Keyframe::new(0.7, 2.0_f32),
                Keyframe::new(1.0, 3.0_f32),
            ]),
            Err(KeyframeError::OffsetsNotMonotonic)
        ));

        let track = Keyframes::try_new([
            Keyframe::new(0.0, 0.0_f32)
                .ease(Easing::steps(2, super::StepPosition::JumpEnd).unwrap()),
            Keyframe::new(0.5, 10.0_f32).ease(Easing::Linear),
            Keyframe::new(1.0, 20.0_f32),
        ])
        .unwrap();

        assert_eq!(track.sample(0.2), 0.0);
        assert_eq!(track.sample(0.3), 5.0);
        assert_eq!(track.sample(0.75), 15.0);
        assert_eq!(track.sample(1.0), 20.0);
    }

    #[test]
    fn discrete_values_switch_only_at_the_requested_progress() {
        let value = Discrete::new("old", "new").switch_at(0.75).unwrap();
        assert_eq!(value.sample(0.749), "old");
        assert_eq!(value.sample(0.75), "new");
        assert!(Discrete::new(0, 1).switch_at(f32::NAN).is_err());
    }

    #[test]
    fn stagger_origins_produce_stable_delays_without_allocating_a_schedule() {
        let interval = Duration::from_millis(20);
        let first = Stagger::new(interval, StaggerOrigin::First);
        let last = Stagger::new(interval, StaggerOrigin::Last);
        let center = Stagger::new(interval, StaggerOrigin::Center);

        assert_eq!(first.delay(3, 5), Duration::from_millis(60));
        assert_eq!(last.delay(3, 5), Duration::from_millis(20));
        assert_eq!(center.delay(2, 5), Duration::ZERO);
        assert_eq!(center.delay(0, 5), Duration::from_millis(40));
        assert_eq!(first.delay(7, 0), Duration::ZERO);
    }

    #[test]
    fn common_gpui_geometry_interpolates_channel_by_channel() {
        let from_size = size(px(10.0), px(20.0));
        let to_size = size(px(30.0), px(60.0));
        assert_eq!(
            from_size.interpolate(&to_size, 0.25),
            size(px(15.0), px(30.0))
        );

        let from = Bounds::new(point(px(0.0), px(10.0)), from_size);
        let to = Bounds::new(point(px(40.0), px(50.0)), to_size);
        assert_eq!(
            from.interpolate(&to, 0.5),
            Bounds::new(point(px(20.0), px(30.0)), size(px(20.0), px(40.0)))
        );

        let _: Point<gpui::Pixels> = from.origin;
        let _: Size<gpui::Pixels> = from.size;

        let transform = MotionTransform::identity().interpolate(
            &MotionTransform {
                translation: point(px(20.0), px(40.0)),
                scale: point(2.0, 0.5),
                rotation_radians: std::f32::consts::PI,
                opacity: 0.0,
            },
            0.5,
        );
        assert_eq!(transform.translation, point(px(10.0), px(20.0)));
        assert_eq!(transform.scale, point(1.5, 0.75));
        assert_eq!(transform.rotation_radians, std::f32::consts::FRAC_PI_2);
        assert_eq!(transform.opacity, 0.5);
    }
}

#[cfg(test)]
mod tests {
    use std::{
        cell::{Cell, RefCell},
        rc::Rc,
        time::Duration,
    };

    use gpui::{
        Empty, IntoElement, Render, TestAppContext, VisualTestContext, WindowHandle, px, size,
    };

    use super::*;

    struct StatusView {
        target: Rc<Cell<f32>>,
        policy: Transition,
        samples: Rc<RefCell<Vec<MotionValue<f32>>>>,
    }

    impl Render for StatusView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(transition_with_status(
                ("status-test", "value"),
                self.target.get(),
                self.policy.clone(),
                window,
                cx,
            ));
            Empty
        }
    }

    struct StatusFixture {
        window: WindowHandle<StatusView>,
        target: Rc<Cell<f32>>,
        samples: Rc<RefCell<Vec<MotionValue<f32>>>>,
    }

    impl StatusFixture {
        fn open(cx: &mut TestAppContext, policy: Transition) -> Self {
            let target = Rc::new(Cell::new(0.0));
            let samples = Rc::new(RefCell::new(Vec::new()));
            let window = cx.open_window(size(px(100.), px(100.)), {
                let target = target.clone();
                let samples = samples.clone();
                move |_, _| StatusView {
                    target,
                    policy,
                    samples,
                }
            });
            cx.run_until_parked();
            Self {
                window,
                target,
                samples,
            }
        }

        fn render(&self, cx: &mut TestAppContext, target: f32) -> MotionValue<f32> {
            self.target.set(target);
            self.window
                .update(cx, |_, window, _| window.refresh())
                .unwrap();
            cx.run_until_parked();
            *self.samples.borrow().last().unwrap()
        }
    }

    #[gpui::test]
    fn status_transition_reports_delay_running_and_finished(cx: &mut TestAppContext) {
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(100)).delay(Duration::from_millis(20)),
        );
        assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Delayed);

        cx.executor().advance_clock(Duration::from_millis(20));
        assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Running);
        cx.executor().advance_clock(Duration::from_millis(100));
        assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Finished);
    }

    #[gpui::test]
    fn negative_delay_samples_a_target_change_inside_its_interval(cx: &mut TestAppContext) {
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(100))
                .delay(SignedDuration::negative(Duration::from_millis(25)))
                .ease(|t| t),
        );
        let sample = fixture.render(cx, 1.0);
        assert_eq!(sample.status, MotionStatus::Running);
        assert_eq!(sample.value, 0.25);
    }

    #[gpui::test]
    fn a_direct_reversal_shortens_the_return_transition(cx: &mut TestAppContext) {
        let fixture =
            StatusFixture::open(cx, Transition::new(Duration::from_millis(100)).ease(|t| t));
        assert_eq!(fixture.render(cx, 1.0).value, 0.0);
        cx.executor().advance_clock(Duration::from_millis(50));
        assert_eq!(fixture.render(cx, 0.0).value, 0.5);
        cx.executor().advance_clock(Duration::from_millis(25));
        assert_eq!(fixture.render(cx, 0.0).value, 0.25);
    }

    #[gpui::test]
    fn repeated_reversals_keep_the_logical_start(cx: &mut TestAppContext) {
        let fixture =
            StatusFixture::open(cx, Transition::new(Duration::from_millis(1000)).ease(|t| t));
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(400));
        assert!((fixture.render(cx, 0.0).value - 0.4).abs() < 1e-6);
        cx.executor().advance_clock(Duration::from_millis(100));
        assert!((fixture.render(cx, 1.0).value - 0.3).abs() < 1e-6);
        cx.executor().advance_clock(Duration::from_millis(100));
        assert!((fixture.render(cx, 0.0).value - 0.4).abs() < 1e-6);
        cx.executor().advance_clock(Duration::from_millis(401));
        assert_eq!(fixture.render(cx, 0.0).status, MotionStatus::Finished);
        assert_eq!(fixture.render(cx, 0.0).value, 0.0);
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(500));
        assert!((fixture.render(cx, 1.0).value - 0.5).abs() < 1e-6);
    }

    #[gpui::test]
    fn reversal_scales_negative_delay(cx: &mut TestAppContext) {
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(1000))
                .delay(SignedDuration::negative(Duration::from_millis(200)))
                .ease(|t| t),
        );
        assert_eq!(fixture.render(cx, 1.0).value, 0.2);
        cx.executor().advance_clock(Duration::from_millis(200));
        // At 0.4, reverse with duration 400ms and delay -80ms.
        assert!((fixture.render(cx, 0.0).value - 0.32).abs() < 1e-6);
        cx.executor().advance_clock(Duration::from_millis(321));
        assert_eq!(fixture.render(cx, 0.0).status, MotionStatus::Finished);
    }

    #[gpui::test]
    fn reversal_uses_absolute_shortening_for_anticipation(cx: &mut TestAppContext) {
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(1000)).ease(|t| if t < 0.5 { -t } else { t }),
        );
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(250));
        assert_eq!(fixture.render(cx, 0.0).status, MotionStatus::Running);
        cx.executor().advance_clock(Duration::from_millis(250));
        assert_eq!(fixture.render(cx, 0.0).status, MotionStatus::Finished);
    }

    #[gpui::test]
    fn non_reversing_retarget_uses_full_duration(cx: &mut TestAppContext) {
        let fixture =
            StatusFixture::open(cx, Transition::new(Duration::from_millis(1000)).ease(|t| t));
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(400));
        fixture.render(cx, 0.0);
        cx.executor().advance_clock(Duration::from_millis(100));
        fixture.render(cx, 2.0);
        cx.executor().advance_clock(Duration::from_millis(500));
        assert!((fixture.render(cx, 2.0).value - 1.15).abs() < 1e-6);
    }

    #[gpui::test]
    fn active_policy_is_retained_until_retarget(cx: &mut TestAppContext) {
        let fixture =
            StatusFixture::open(cx, Transition::new(Duration::from_millis(1000)).ease(|t| t));
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(400));
        fixture
            .window
            .update(cx, |view, _, _| {
                view.policy = Transition::new(Duration::from_millis(1000))
                    .ease(|t| t * t)
                    .delay(SignedDuration::negative(Duration::from_millis(200)));
            })
            .unwrap();
        assert!((fixture.render(cx, 1.0).value - 0.4).abs() < 1e-6);
        // Old linear sample 0.4; new quadratic curve starts at 0.2^2.
        assert!((fixture.render(cx, 2.0).value - 0.464).abs() < 1e-6);
    }

    #[gpui::test]
    fn reversal_keeps_positive_delay(cx: &mut TestAppContext) {
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(1000))
                .delay(Duration::from_millis(200))
                .ease(|t| t),
        );
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(600));
        assert!((fixture.render(cx, 0.0).value - 0.4).abs() < 1e-6);
        cx.executor().advance_clock(Duration::from_millis(100));
        assert_eq!(fixture.render(cx, 0.0).status, MotionStatus::Delayed);
        cx.executor().advance_clock(Duration::from_millis(501));
        assert_eq!(fixture.render(cx, 0.0).status, MotionStatus::Finished);
    }

    #[gpui::test]
    fn effects_opt_in_keeps_timing_under_reduced_motion(cx: &mut TestAppContext) {
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(1000))
                .ease(|t| t)
                .reduced_motion(ReducedMotion::Continue),
        );
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(200));
        cx.update(|cx| cx.set_reduce_motion(true));
        assert!((fixture.render(cx, 1.0).value - 0.2).abs() < 1e-6);
        cx.update(|cx| assert!(cx.reduce_motion()));
        cx.executor().advance_clock(Duration::from_millis(800));
        assert_eq!(fixture.render(cx, 1.0).status, MotionStatus::Finished);
        fixture.render(cx, 0.0);
        cx.executor().advance_clock(Duration::from_millis(500));
        assert!((fixture.render(cx, 0.0).value - 0.5).abs() < 1e-6);
        cx.update(|cx| cx.set_reduce_motion(false));
        assert!((fixture.render(cx, 0.0).value - 0.5).abs() < 1e-6);
    }

    #[gpui::test]
    fn current_reduced_motion_policy_and_zero_duration_take_effect(cx: &mut TestAppContext) {
        cx.update(|cx| cx.set_reduce_motion(true));
        let fixture = StatusFixture::open(
            cx,
            Transition::new(Duration::from_millis(1000))
                .ease(|t| t)
                .reduced_motion(ReducedMotion::Continue),
        );
        fixture.render(cx, 1.0);
        cx.executor().advance_clock(Duration::from_millis(200));
        fixture
            .window
            .update(cx, |view, _, _| {
                view.policy = view.policy.clone().reduced_motion(ReducedMotion::Finish);
            })
            .unwrap();
        assert_eq!(fixture.render(cx, 1.0).value, 1.0);
        fixture
            .window
            .update(cx, |view, _, _| {
                view.policy = view.policy.clone().reduced_motion(ReducedMotion::Continue);
            })
            .unwrap();
        assert_eq!(fixture.render(cx, 0.0).value, 1.0);
        cx.executor().advance_clock(Duration::from_millis(200));
        assert!((fixture.render(cx, 0.0).value - 0.8).abs() < 1e-6);
        fixture
            .window
            .update(cx, |view, _, _| {
                view.policy =
                    Transition::new(Duration::ZERO).reduced_motion(ReducedMotion::Continue);
            })
            .unwrap();
        assert_eq!(fixture.render(cx, 0.0).value, 0.0);
    }

    struct PairView {
        target: f32,
        policy: Transition,
        state: TransitionState<f32>,
        samples: Rc<RefCell<Vec<(MotionValue<f32>, MotionValue<f32>)>>>,
    }

    impl Render for PairView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            let keyed = transition_with_status(
                ("pair-test", "value"),
                self.target,
                self.policy.clone(),
                window,
                cx,
            );
            let owned = self
                .state
                .sample(self.target, self.policy.clone(), window, cx);
            self.samples.borrow_mut().push((keyed, owned));
            Empty
        }
    }

    #[gpui::test]
    fn transition_state_matches_keyed_transition_retarget_reverse_and_delay(
        cx: &mut TestAppContext,
    ) {
        for policy in [
            Transition::new(Duration::from_millis(100)).easing(Easing::Linear),
            Transition::new(Duration::from_millis(100))
                .easing(Easing::Ease)
                .delay(SignedDuration::negative(Duration::from_millis(10))),
        ] {
            let samples = Rc::new(RefCell::new(Vec::new()));
            let (view, cx) = cx.add_window_view(|_, _| PairView {
                target: 0.,
                policy,
                state: TransitionState::default(),
                samples: samples.clone(),
            });
            for (millis, target) in [(0, 1.), (40, 1.), (0, 0.), (20, 0.), (0, 1.), (100, 1.)] {
                cx.executor().advance_clock(Duration::from_millis(millis));
                cx.update(|window, cx| {
                    view.update(cx, |view, _| view.target = target);
                    window.refresh();
                    window.draw(cx).clear(cx);
                });
                let (expected, actual) = *samples.borrow().last().unwrap();
                assert_eq!(actual.status, expected.status);
                assert!((actual.value - expected.value).abs() < 0.00001);
            }
        }
    }

    struct PersistentTransitionView {
        state: TransitionState<f32>,
        policy: Transition,
        mounted: bool,
        target: f32,
        sampled: Rc<Cell<Option<MotionValue<f32>>>>,
    }

    impl Render for PersistentTransitionView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            if self.mounted {
                self.sampled.set(Some(self.state.sample(
                    self.target,
                    self.policy.clone(),
                    window,
                    cx,
                )));
            }
            Empty
        }
    }

    struct Persistent {
        view: gpui::Entity<PersistentTransitionView>,
        sampled: Rc<Cell<Option<MotionValue<f32>>>>,
    }

    impl Persistent {
        fn open(cx: &mut TestAppContext, policy: Transition) -> (Self, &mut VisualTestContext) {
            let sampled = Rc::new(Cell::new(None));
            let (view, cx) = cx.add_window_view(|_, _| PersistentTransitionView {
                state: TransitionState::default(),
                policy,
                mounted: true,
                target: 0.,
                sampled: sampled.clone(),
            });
            (Self { view, sampled }, cx)
        }

        /// Draws once with `update` applied, returning the sample (if mounted)
        /// and how many animation frames that draw requested.
        fn draw(
            &self,
            cx: &mut VisualTestContext,
            update: impl FnOnce(&mut PersistentTransitionView),
        ) -> (Option<MotionValue<f32>>, usize) {
            self.sampled.set(None);
            cx.update(|window, cx| {
                window.simulate_next_frame(cx);
                self.view.update(cx, |view, _| update(view));
                window.refresh();
                window.draw(cx).clear(cx);
                (self.sampled.get(), window.simulate_next_frame(cx))
            })
        }
    }

    #[gpui::test]
    fn transition_state_requests_frames_only_while_delayed_or_running(cx: &mut TestAppContext) {
        let (fixture, cx) = Persistent::open(
            cx,
            Transition::new(Duration::from_millis(100)).delay(Duration::from_millis(20)),
        );
        let (adopted, frames) = fixture.draw(cx, |_| {});
        assert_eq!(adopted.unwrap().status, MotionStatus::Idle);
        assert_eq!(frames, 0, "the first sample adopts its target");

        let (delayed, frames) = fixture.draw(cx, |view| view.target = 1.);
        assert_eq!(delayed.unwrap().status, MotionStatus::Delayed);
        assert!(frames > 0, "a delayed transition requests the next frame");

        cx.executor().advance_clock(Duration::from_millis(70));
        let (running, frames) = fixture.draw(cx, |_| {});
        assert_eq!(running.unwrap().status, MotionStatus::Running);
        assert!(frames > 0, "a running transition requests the next frame");

        cx.executor().advance_clock(Duration::from_millis(50));
        let (finished, frames) = fixture.draw(cx, |_| {});
        assert_eq!(finished.unwrap().status, MotionStatus::Finished);
        assert_eq!(frames, 0, "a settled transition requests no frame");
    }

    #[gpui::test]
    fn transition_state_survives_unmount_and_reverses_on_remount(cx: &mut TestAppContext) {
        let (fixture, cx) = Persistent::open(
            cx,
            Transition::new(Duration::from_millis(100)).easing(Easing::Linear),
        );
        fixture.draw(cx, |view| view.target = 1.);
        cx.executor().advance_clock(Duration::from_millis(40));
        let (sample, _) = fixture.draw(cx, |_| {});
        assert!((sample.unwrap().value - 0.4).abs() < 0.00001);

        let (sample, frames) = fixture.draw(cx, |view| view.mounted = false);
        assert_eq!(sample, None);
        assert_eq!(frames, 0, "an unmounted state requests no frames");

        // The target changes while the element is not rendered; the clock keeps
        // the forward transition, and the reversal starts at the next sample.
        cx.executor().advance_clock(Duration::from_millis(30));
        fixture.draw(cx, |view| view.target = 0.);
        let (sample, frames) = fixture.draw(cx, |view| view.mounted = true);
        let sample = sample.unwrap();
        assert_eq!(sample.status, MotionStatus::Running);
        assert!((sample.value - 0.7).abs() < 0.00001);
        assert!(frames > 0);

        cx.executor().advance_clock(Duration::from_millis(35));
        let (sample, _) = fixture.draw(cx, |_| {});
        assert!(
            (sample.unwrap().value - 0.35).abs() < 0.00001,
            "the 70ms shortened reversal continues after remount"
        );
        cx.executor().advance_clock(Duration::from_millis(35));
        let (sample, frames) = fixture.draw(cx, |_| {});
        assert_eq!(
            sample.unwrap(),
            MotionValue {
                value: 0.,
                status: MotionStatus::Finished
            }
        );
        assert_eq!(frames, 0);
    }

    struct KeyframeView {
        track: Keyframes<f32>,
        timing: Timing,
        samples: Rc<RefCell<Vec<MotionValue<f32>>>>,
    }

    impl Render for KeyframeView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(animate_keyframes(
                "keyframe-test",
                &self.track,
                self.timing.clone(),
                window,
                cx,
            ));
            Empty
        }
    }

    #[gpui::test]
    fn keyed_keyframes_follow_timing_and_stop_after_completion(cx: &mut TestAppContext) {
        let samples = Rc::new(RefCell::new(Vec::new()));
        let window = cx.open_window(size(px(100.), px(100.)), {
            let samples = samples.clone();
            move |_, _| KeyframeView {
                track: Keyframes::try_new([Keyframe::new(0.0, 0.0), Keyframe::new(1.0, 10.0)])
                    .unwrap(),
                timing: Timing::new(Duration::from_millis(100)),
                samples,
            }
        });
        cx.run_until_parked();
        assert_eq!(samples.borrow().last().unwrap().value, 0.0);
        assert_eq!(
            samples.borrow().last().unwrap().status,
            MotionStatus::Running
        );

        cx.executor().advance_clock(Duration::from_millis(50));
        assert_eq!(
            window
                .update(cx, |_, window, cx| window.simulate_next_frame(cx))
                .unwrap(),
            1
        );
        cx.run_until_parked();
        assert_eq!(samples.borrow().last().unwrap().value, 5.0);

        cx.executor().advance_clock(Duration::from_millis(50));
        window.update(cx, |_, window, _| window.refresh()).unwrap();
        cx.run_until_parked();
        assert_eq!(
            samples.borrow().last().unwrap().status,
            MotionStatus::Finished
        );
        window
            .update(cx, |_, window, cx| window.simulate_next_frame(cx))
            .unwrap();
        cx.run_until_parked();
        assert_eq!(
            window
                .update(cx, |_, window, cx| window.simulate_next_frame(cx))
                .unwrap(),
            0
        );
    }

    struct PresenceView {
        present: Rc<Cell<bool>>,
        samples: Rc<RefCell<Vec<PresenceSample>>>,
    }

    impl Render for PresenceView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(
                Presence::new("presence-test", self.present.get())
                    .transition(Transition::new(Duration::from_millis(100)).ease(|t| t))
                    .sample(window, cx),
            );
            Empty
        }
    }

    struct PresenceFixture {
        window: WindowHandle<PresenceView>,
        present: Rc<Cell<bool>>,
        samples: Rc<RefCell<Vec<PresenceSample>>>,
    }

    impl PresenceFixture {
        fn open(cx: &mut TestAppContext, initially_present: bool) -> Self {
            let present = Rc::new(Cell::new(initially_present));
            let samples = Rc::new(RefCell::new(Vec::new()));
            let window = cx.open_window(size(px(100.), px(100.)), {
                let present = present.clone();
                let samples = samples.clone();
                move |_, _| PresenceView { present, samples }
            });
            cx.run_until_parked();
            Self {
                window,
                present,
                samples,
            }
        }

        fn render(&self, cx: &mut TestAppContext, present: bool) -> PresenceSample {
            self.present.set(present);
            self.window
                .update(cx, |_, window, _| window.refresh())
                .unwrap();
            cx.run_until_parked();
            *self.samples.borrow().last().unwrap()
        }
    }

    #[gpui::test]
    fn presence_enters_exits_and_only_unmounts_after_exit(cx: &mut TestAppContext) {
        let fixture = PresenceFixture::open(cx, true);
        let entering = *fixture.samples.borrow().last().unwrap();
        assert_eq!(entering.phase, PresencePhase::Entering);
        assert_eq!(entering.progress, 0.0);
        assert!(entering.should_render());

        cx.executor().advance_clock(Duration::from_millis(100));
        let present = fixture.render(cx, true);
        assert_eq!(present.phase, PresencePhase::Present);
        assert_eq!(present.progress, 1.0);

        let exiting = fixture.render(cx, false);
        assert_eq!(exiting.phase, PresencePhase::Exiting);
        assert_eq!(exiting.progress, 1.0);
        assert!(exiting.should_render());

        cx.executor().advance_clock(Duration::from_millis(100));
        let absent = fixture.render(cx, false);
        assert_eq!(absent.phase, PresencePhase::Absent);
        assert_eq!(absent.progress, 0.0);
        assert!(!absent.should_render());
    }

    #[gpui::test]
    fn presence_reentry_reverses_from_the_exit_sample(cx: &mut TestAppContext) {
        let fixture = PresenceFixture::open(cx, true);
        cx.executor().advance_clock(Duration::from_millis(100));
        fixture.render(cx, true);
        fixture.render(cx, false);
        cx.executor().advance_clock(Duration::from_millis(40));
        let reentering = fixture.render(cx, true);

        assert_eq!(reentering.phase, PresencePhase::Entering);
        assert_eq!(reentering.progress, 0.6);
    }

    #[gpui::test]
    fn reduced_motion_resolves_presence_without_a_pending_frame(cx: &mut TestAppContext) {
        cx.update(|cx| cx.set_reduce_motion(true));
        let fixture = PresenceFixture::open(cx, true);
        assert_eq!(
            fixture.samples.borrow().last().unwrap().phase,
            PresencePhase::Present
        );
        assert_eq!(
            fixture
                .window
                .update(cx, |_, window, cx| window.simulate_next_frame(cx))
                .unwrap(),
            0
        );
        assert_eq!(fixture.render(cx, false).phase, PresencePhase::Absent);
    }

    struct SequenceView {
        steps: Rc<RefCell<Vec<SequenceStep<f32>>>>,
        samples: Rc<RefCell<Vec<SequenceSample<f32>>>>,
    }

    impl Render for SequenceView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(
                Sequence::new("sequence-test", 0.0)
                    .with_steps(self.steps.borrow().iter().cloned())
                    .sample(window, cx),
            );
            Empty
        }
    }

    struct SequenceFixture {
        window: WindowHandle<SequenceView>,
        steps: Rc<RefCell<Vec<SequenceStep<f32>>>>,
        samples: Rc<RefCell<Vec<SequenceSample<f32>>>>,
    }

    impl SequenceFixture {
        fn open(cx: &mut TestAppContext, steps: Vec<SequenceStep<f32>>) -> Self {
            let steps = Rc::new(RefCell::new(steps));
            let samples = Rc::new(RefCell::new(Vec::new()));
            let window = cx.open_window(size(px(100.), px(100.)), {
                let steps = steps.clone();
                let samples = samples.clone();
                move |_, _| SequenceView { steps, samples }
            });
            cx.run_until_parked();
            Self {
                window,
                steps,
                samples,
            }
        }

        fn linear(millis: u64) -> Transition {
            Transition::new(Duration::from_millis(millis)).ease(|t| t)
        }

        fn last(&self) -> SequenceSample<f32> {
            *self.samples.borrow().last().unwrap()
        }

        fn render(&self, cx: &mut TestAppContext) -> SequenceSample<f32> {
            self.window
                .update(cx, |_, window, _| window.refresh())
                .unwrap();
            cx.run_until_parked();
            self.last()
        }

        fn advance(&self, cx: &mut TestAppContext, millis: u64) -> SequenceSample<f32> {
            cx.executor().advance_clock(Duration::from_millis(millis));
            self.render(cx)
        }

        fn pending_frame(&self, cx: &mut TestAppContext) -> usize {
            self.window
                .update(cx, |_, window, cx| window.simulate_next_frame(cx))
                .unwrap()
        }
    }

    fn assert_sample(sample: SequenceSample<f32>, value: f32, step: usize, status: MotionStatus) {
        assert_eq!(
            (*sample.value(), sample.step(), sample.status()),
            (value, step, status)
        );
    }

    #[gpui::test]
    fn sequence_steps_advance_in_order_at_their_boundaries(cx: &mut TestAppContext) {
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
                SequenceStep::new(
                    20.0,
                    SequenceFixture::linear(100).delay(Duration::from_millis(50)),
                ),
            ],
        );
        assert_sample(fixture.last(), 0.0, 0, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 50), 5.0, 0, MotionStatus::Running);

        // The first step ends and the second begins within one frame; nothing
        // reports the first step as finished in between.
        assert_sample(fixture.advance(cx, 50), 10.0, 1, MotionStatus::Delayed);
        assert_sample(fixture.advance(cx, 50), 10.0, 1, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 50), 15.0, 1, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 50), 20.0, 1, MotionStatus::Finished);
    }

    #[gpui::test]
    fn a_sequence_starts_its_next_step_where_the_previous_ended_not_at_the_frame(
        cx: &mut TestAppContext,
    ) {
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
                SequenceStep::new(20.0, SequenceFixture::linear(100)),
            ],
        );
        // One frame at 50 ms, the next at 175 ms: the boundary at 100 ms fell
        // between them, and the second step is sampled as if it started there.
        fixture.advance(cx, 50);
        assert_sample(fixture.advance(cx, 125), 17.5, 1, MotionStatus::Running);
    }

    #[gpui::test]
    fn zero_duration_steps_complete_within_the_frame_that_reaches_them(cx: &mut TestAppContext) {
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(5.0, SequenceFixture::linear(0)),
                SequenceStep::new(6.0, SequenceFixture::linear(0)),
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
            ],
        );
        assert_sample(fixture.last(), 6.0, 2, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 50), 8.0, 2, MotionStatus::Running);
    }

    #[gpui::test]
    fn a_sequence_reports_finished_once_and_then_stops_requesting_frames(cx: &mut TestAppContext) {
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
                SequenceStep::new(20.0, SequenceFixture::linear(100)),
            ],
        );
        assert_eq!(fixture.pending_frame(cx), 1);
        cx.run_until_parked();

        cx.executor().advance_clock(Duration::from_millis(100));
        assert_eq!(fixture.pending_frame(cx), 1);
        cx.run_until_parked();
        assert_eq!(fixture.last().status(), MotionStatus::Running);
        assert!(
            fixture
                .samples
                .borrow()
                .iter()
                .all(|sample| !sample.is_finished()),
            "the first step's end must not read as the sequence finishing"
        );

        assert_sample(fixture.advance(cx, 100), 20.0, 1, MotionStatus::Finished);
        fixture.pending_frame(cx);
        cx.run_until_parked();
        assert_eq!(fixture.pending_frame(cx), 0);
        assert_sample(fixture.advance(cx, 1_000), 20.0, 1, MotionStatus::Finished);
    }

    #[gpui::test]
    fn reduced_motion_adopts_a_sequences_last_target_without_requesting_a_frame(
        cx: &mut TestAppContext,
    ) {
        cx.update(|cx| cx.set_reduce_motion(true));
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
                SequenceStep::new(20.0, SequenceFixture::linear(100)),
            ],
        );
        assert_sample(fixture.last(), 20.0, 1, MotionStatus::Finished);
        assert_eq!(fixture.pending_frame(cx), 0);
    }

    #[gpui::test]
    fn a_changed_step_target_restarts_the_sequence_from_the_sampled_value(cx: &mut TestAppContext) {
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
                SequenceStep::new(20.0, SequenceFixture::linear(100)),
            ],
        );
        fixture.advance(cx, 150);
        assert_sample(fixture.last(), 15.0, 1, MotionStatus::Running);

        *fixture.steps.borrow_mut() = vec![
            SequenceStep::new(10.0, SequenceFixture::linear(100)),
            SequenceStep::new(35.0, SequenceFixture::linear(100)),
        ];
        assert_sample(fixture.render(cx), 15.0, 0, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 50), 12.5, 0, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 100), 22.5, 1, MotionStatus::Running);

        // Fewer steps than the one being played is a different sequence too.
        *fixture.steps.borrow_mut() = vec![SequenceStep::new(0.0, SequenceFixture::linear(100))];
        assert_sample(fixture.render(cx), 22.5, 0, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 100), 0.0, 0, MotionStatus::Finished);
    }

    #[gpui::test]
    fn a_change_to_a_step_not_being_played_does_not_restart_the_sequence(cx: &mut TestAppContext) {
        let fixture = SequenceFixture::open(
            cx,
            vec![
                SequenceStep::new(10.0, SequenceFixture::linear(100)),
                SequenceStep::new(20.0, SequenceFixture::linear(100)),
            ],
        );
        fixture.advance(cx, 50);
        *fixture.steps.borrow_mut() = vec![
            SequenceStep::new(10.0, SequenceFixture::linear(100)),
            SequenceStep::new(30.0, SequenceFixture::linear(100)),
        ];
        assert_sample(fixture.render(cx), 5.0, 0, MotionStatus::Running);
        assert_sample(fixture.advance(cx, 100), 20.0, 1, MotionStatus::Running);
    }

    struct SingleStepView {
        armed: Rc<Cell<bool>>,
        samples: Rc<RefCell<Vec<(SequenceSample<f32>, MotionValue<f32>)>>>,
    }

    impl Render for SingleStepView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            let policy = Transition::new(Duration::from_millis(100))
                .delay(Duration::from_millis(20))
                .easing(Easing::EaseInOut);
            // A plain transition adopts its first target where a sequence
            // plays from `from` at once, so the transition is primed at 0.0
            // and both leave for 10.0 on the frame that arms the view.
            if !self.armed.get() {
                transition_with_status("plain", 0.0, policy, window, cx);
                return Empty;
            }
            let sequence = Sequence::new("single-step", 0.0)
                .with_step(10.0, policy.clone())
                .sample(window, cx);
            let plain = transition_with_status("plain", 10.0, policy, window, cx);
            self.samples.borrow_mut().push((sequence, plain));
            Empty
        }
    }

    #[gpui::test]
    fn a_single_step_sequence_matches_a_plain_transition(cx: &mut TestAppContext) {
        let armed = Rc::new(Cell::new(false));
        let samples = Rc::new(RefCell::new(Vec::new()));
        let window = cx.open_window(size(px(100.), px(100.)), {
            let armed = armed.clone();
            let samples = samples.clone();
            move |_, _| SingleStepView { armed, samples }
        });
        cx.run_until_parked();
        armed.set(true);
        for millis in [0, 10, 30, 70, 120] {
            cx.executor().advance_clock(Duration::from_millis(millis));
            window.update(cx, |_, window, _| window.refresh()).unwrap();
            cx.run_until_parked();
            let (sequence, plain) = *samples.borrow().last().unwrap();
            assert_eq!(*sequence.value(), plain.value, "value after {millis} ms");
            assert_eq!(sequence.status(), plain.status, "status after {millis} ms");
            assert_eq!(sequence.step(), 0);
        }
    }

    #[gpui::test]
    fn an_empty_sequence_idles_at_its_starting_value(cx: &mut TestAppContext) {
        let fixture = SequenceFixture::open(cx, Vec::new());
        assert_sample(fixture.last(), 0.0, 0, MotionStatus::Idle);
        assert_eq!(fixture.pending_frame(cx), 0);
    }

    #[test]
    fn transition_ids_accept_element_like_scalars_and_named_channels() {
        assert_eq!(
            TransitionId::from("opacity"),
            TransitionId::from(ElementId::from("opacity"))
        );
        assert_ne!(
            TransitionId::from(("terms", "fill")),
            TransitionId::from(("terms", "mark-opacity"))
        );
        let _: TransitionId = 7usize.into();
        let _: TransitionId = 7i32.into();
    }

    struct TestView {
        target: Rc<Cell<f32>>,
        duration: Duration,
        samples: Rc<RefCell<Vec<f32>>>,
    }

    impl Render for TestView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(transition(
                ("test", "value"),
                self.target.get(),
                Transition::new(self.duration).ease(|t| t),
                window,
                cx,
            ));
            Empty
        }
    }

    struct DelayedView {
        target: Rc<Cell<f32>>,
        samples: Rc<RefCell<Vec<f32>>>,
    }

    impl Render for DelayedView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(transition(
                ("delayed-test", "value"),
                self.target.get(),
                Transition::new(Duration::from_millis(100))
                    .delay(Duration::from_millis(50))
                    .ease(|t| t),
                window,
                cx,
            ));
            Empty
        }
    }

    struct Fixture {
        window: WindowHandle<TestView>,
        target: Rc<Cell<f32>>,
        samples: Rc<RefCell<Vec<f32>>>,
    }

    impl Fixture {
        fn open(cx: &mut TestAppContext, duration: Duration) -> Self {
            let target = Rc::new(Cell::new(0.0));
            let samples = Rc::new(RefCell::new(Vec::new()));
            let window = cx.open_window(size(px(100.), px(100.)), {
                let target = target.clone();
                let samples = samples.clone();
                move |_, _| TestView {
                    target,
                    duration,
                    samples,
                }
            });
            cx.run_until_parked();
            Self {
                window,
                target,
                samples,
            }
        }

        fn render(&self, cx: &mut TestAppContext, target: f32) -> f32 {
            self.target.set(target);
            self.window
                .update(cx, |_, window, _| window.refresh())
                .unwrap();
            cx.run_until_parked();
            *self.samples.borrow().last().unwrap()
        }

        fn pending_frame(&self, cx: &mut TestAppContext) -> usize {
            self.window
                .update(cx, |_, window, cx| window.simulate_next_frame(cx))
                .unwrap()
        }
    }

    #[gpui::test]
    fn a_zero_duration_target_change_is_immediate(cx: &mut TestAppContext) {
        let fixture = Fixture::open(cx, Duration::ZERO);
        assert_eq!(fixture.render(cx, 1.0), 1.0);
    }

    #[gpui::test]
    fn a_changed_target_transitions_over_time(cx: &mut TestAppContext) {
        let duration = Duration::from_millis(100);
        let fixture = Fixture::open(cx, duration);
        assert_eq!(fixture.render(cx, 10.0), 0.0);

        cx.executor().advance_clock(Duration::from_millis(50));
        assert_eq!(fixture.render(cx, 10.0), 5.0);
    }

    #[gpui::test]
    fn requested_animation_frames_resample_without_manual_refresh(cx: &mut TestAppContext) {
        let duration = Duration::from_millis(100);
        let fixture = Fixture::open(cx, duration);
        assert_eq!(fixture.render(cx, 10.0), 0.0);

        cx.executor().advance_clock(Duration::from_millis(50));
        assert_eq!(fixture.pending_frame(cx), 1);
        cx.run_until_parked();

        assert_eq!(*fixture.samples.borrow().last().unwrap(), 5.0);
    }

    #[gpui::test]
    fn reversing_uses_the_current_sample_and_shortens_the_return(cx: &mut TestAppContext) {
        let duration = Duration::from_millis(100);
        let fixture = Fixture::open(cx, duration);
        assert_eq!(fixture.render(cx, 10.0), 0.0);

        cx.executor().advance_clock(Duration::from_millis(50));
        assert_eq!(fixture.render(cx, 0.0), 5.0);
        cx.executor().advance_clock(Duration::from_millis(25));
        assert_eq!(fixture.render(cx, 0.0), 2.5);
    }

    #[gpui::test]
    fn delay_holds_the_previous_value_before_interpolation(cx: &mut TestAppContext) {
        let target = Rc::new(Cell::new(0.0));
        let samples = Rc::new(RefCell::new(Vec::new()));
        let window = cx.open_window(size(px(100.), px(100.)), {
            let target = target.clone();
            let samples = samples.clone();
            move |_, _| DelayedView { target, samples }
        });
        cx.run_until_parked();

        target.set(10.0);
        window.update(cx, |_, window, _| window.refresh()).unwrap();
        cx.run_until_parked();
        assert_eq!(*samples.borrow().last().unwrap(), 0.0);

        cx.executor().advance_clock(Duration::from_millis(50));
        window.update(cx, |_, window, _| window.refresh()).unwrap();
        cx.run_until_parked();
        assert_eq!(*samples.borrow().last().unwrap(), 0.0);

        cx.executor().advance_clock(Duration::from_millis(50));
        window.update(cx, |_, window, _| window.refresh()).unwrap();
        cx.run_until_parked();
        assert_eq!(*samples.borrow().last().unwrap(), 5.0);
    }

    #[gpui::test]
    fn a_completed_transition_stops_requesting_frames(cx: &mut TestAppContext) {
        let duration = Duration::from_millis(100);
        let fixture = Fixture::open(cx, duration);
        fixture.render(cx, 1.0);
        assert_eq!(fixture.pending_frame(cx), 1);

        cx.executor().advance_clock(duration);
        assert_eq!(fixture.render(cx, 1.0), 1.0);
        fixture.pending_frame(cx);
        cx.run_until_parked();
        assert_eq!(fixture.pending_frame(cx), 0);
    }

    #[gpui::test]
    fn reduced_motion_adopts_the_target_without_requesting_a_frame(cx: &mut TestAppContext) {
        cx.update(|cx| cx.set_reduce_motion(true));
        let duration = Duration::from_millis(100);
        let fixture = Fixture::open(cx, duration);
        assert_eq!(fixture.render(cx, 1.0), 1.0);
        assert_eq!(fixture.pending_frame(cx), 0);
    }

    struct SpringView {
        target: Rc<Cell<f32>>,
        policy: Rc<Cell<Spring>>,
        samples: Rc<RefCell<Vec<f32>>>,
    }

    impl Render for SpringView {
        fn render(
            &mut self,
            window: &mut Window,
            cx: &mut gpui::Context<Self>,
        ) -> impl IntoElement {
            self.samples.borrow_mut().push(spring(
                ("spring-test", "value"),
                self.target.get(),
                self.policy.get(),
                window,
                cx,
            ));
            Empty
        }
    }

    struct SpringFixture {
        window: WindowHandle<SpringView>,
        target: Rc<Cell<f32>>,
        policy: Rc<Cell<Spring>>,
        samples: Rc<RefCell<Vec<f32>>>,
    }

    impl SpringFixture {
        fn open(cx: &mut TestAppContext, policy: Spring) -> Self {
            let target = Rc::new(Cell::new(0.0));
            let policy = Rc::new(Cell::new(policy));
            let samples = Rc::new(RefCell::new(Vec::new()));
            let window = cx.open_window(size(px(100.), px(100.)), {
                let target = target.clone();
                let policy = policy.clone();
                let samples = samples.clone();
                move |_, _| SpringView {
                    target,
                    policy,
                    samples,
                }
            });
            cx.run_until_parked();
            Self {
                window,
                target,
                policy,
                samples,
            }
        }

        fn render(&self, cx: &mut TestAppContext, target: f32) -> f32 {
            self.target.set(target);
            self.window
                .update(cx, |_, window, _| window.refresh())
                .unwrap();
            cx.run_until_parked();
            *self.samples.borrow().last().unwrap()
        }

        fn advance(&self, cx: &mut TestAppContext, millis: u64, target: f32) -> f32 {
            cx.executor().advance_clock(Duration::from_millis(millis));
            self.render(cx, target)
        }

        fn pending_frame(&self, cx: &mut TestAppContext) -> usize {
            self.window
                .update(cx, |_, window, cx| window.simulate_next_frame(cx))
                .unwrap()
        }
    }

    #[gpui::test]
    fn a_spring_adopts_its_first_target_immediately(cx: &mut TestAppContext) {
        let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
        assert_eq!(*fixture.samples.borrow().first().unwrap(), 0.0);
    }

    #[gpui::test]
    fn a_spring_travels_toward_its_target_over_time(cx: &mut TestAppContext) {
        let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
        assert_eq!(fixture.render(cx, 1.0), 0.0);

        let early = fixture.advance(cx, 50, 1.0);
        let late = fixture.advance(cx, 50, 1.0);
        assert!(
            0.0 < early && early < late && late < 1.0,
            "expected monotonic approach, got {early} then {late}"
        );
    }

    #[gpui::test]
    fn a_reversed_spring_keeps_its_momentum_before_turning_around(cx: &mut TestAppContext) {
        let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
        fixture.render(cx, 1.0);
        let reversed_at = fixture.advance(cx, 100, 1.0);

        // Retarget mid-flight. A duration-based transition restarts its easing
        // here and moves away from 1.0 on the very next frame.
        assert_eq!(fixture.render(cx, 0.0), reversed_at);

        let next = fixture.advance(cx, 16, 0.0);
        assert!(
            next > reversed_at,
            "expected the spring to carry its velocity past {reversed_at}, got {next}"
        );

        assert_eq!(fixture.advance(cx, 1_000, 0.0), 0.0);
    }

    #[gpui::test]
    fn a_bouncy_spring_overshoots_its_target(cx: &mut TestAppContext) {
        let fixture = SpringFixture::open(
            cx,
            Spring::new(Duration::from_millis(350)).with_damping(0.7),
        );
        fixture.render(cx, 1.0);
        for _ in 0..30 {
            fixture.advance(cx, 16, 1.0);
        }

        let peak = fixture
            .samples
            .borrow()
            .iter()
            .copied()
            .fold(f32::MIN, f32::max);
        assert!(peak > 1.0, "expected an overshoot past 1.0, got {peak}");
    }

    #[gpui::test]
    fn a_settled_spring_stops_requesting_frames(cx: &mut TestAppContext) {
        let fixture = SpringFixture::open(cx, Spring::new(Duration::from_millis(300)));
        fixture.render(cx, 1.0);
        assert_eq!(fixture.pending_frame(cx), 1);

        assert_eq!(fixture.advance(cx, 2_000, 1.0), 1.0);
        fixture.pending_frame(cx);
        cx.run_until_parked();
        assert_eq!(fixture.pending_frame(cx), 0);
    }

    #[gpui::test]
    fn a_spring_that_is_not_travelling_adopts_its_target_on_the_spot(cx: &mut TestAppContext) {
        let travelling = Spring::new(Duration::from_millis(300));
        let fixture = SpringFixture::open(cx, travelling.with_travel(false));

        assert_eq!(fixture.render(cx, 1.0), 1.0);
        assert_eq!(fixture.pending_frame(cx), 0);
        assert_eq!(fixture.advance(cx, 100, 5.0), 5.0);

        // Travel resumes from the value the suspension left behind. A spring
        // that had kept the state it held beforehand would jump back to it here.
        fixture.policy.set(travelling);
        assert_eq!(fixture.render(cx, 6.0), 5.0);
        let next = fixture.advance(cx, 50, 6.0);
        assert!(
            5.0 < next && next < 6.0,
            "expected travel to resume from 5.0, got {next}"
        );
    }

    #[gpui::test]
    fn a_zero_response_spring_resolves_instead_of_dividing_by_its_period(cx: &mut TestAppContext) {
        let fixture = SpringFixture::open(cx, Spring::new(Duration::ZERO));
        assert_eq!(fixture.render(cx, 1.0), 1.0);
        assert_eq!(fixture.pending_frame(cx), 0);
    }

    #[test]
    fn spring_rejects_non_finite_or_negative_physical_parameters() {
        let spring = Spring::new(Duration::from_millis(300));

        assert_eq!(
            spring.try_with_damping(f32::NAN).unwrap_err(),
            SpringError::InvalidDamping
        );
        assert_eq!(
            spring.try_with_damping(-0.1).unwrap_err(),
            SpringError::InvalidDamping
        );
        assert_eq!(
            spring.try_with_epsilon(f32::INFINITY).unwrap_err(),
            SpringError::InvalidEpsilon
        );
        assert_eq!(
            spring.try_with_epsilon(-0.1).unwrap_err(),
            SpringError::InvalidEpsilon
        );
    }

    #[test]
    fn spring_reports_its_unit_specific_settling_tolerance() {
        let normalized = Spring::new(Duration::from_millis(180));
        let pixels = Spring::new(Duration::from_millis(180)).with_epsilon(0.1);

        assert!(normalized.epsilon() < 0.01);
        assert_eq!(pixels.epsilon(), 0.1);
    }

    #[gpui::test]
    fn reduced_motion_adopts_the_spring_target_without_requesting_a_frame(cx: &mut TestAppContext) {
        cx.update(|cx| cx.set_reduce_motion(true));
        let fixture = SpringFixture::open(
            cx,
            Spring::new(Duration::from_millis(350)).with_damping(0.7),
        );
        assert_eq!(fixture.render(cx, 1.0), 1.0);
        assert_eq!(fixture.pending_frame(cx), 0);
    }
}