nsh-core 0.7.2

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
//! What animates on one view, without the view: `LayoutAnimation`
//! (frames, insertions, removals), style `transition`s (a text's color
//! included) and keyframe `animation`s (`spin`, `ping`, `pulse`,
//! `bounce`), stepped by a desktop backend's frame clock (Windows, GPUI,
//! Linux and macOS share it).
//!
//! A backend keeps a [`Live`] beside a view that animates and runs a
//! frame callback while it has something to do; other views carry
//! nothing and cost nothing. The backend tells [`Live`] what changed
//! ([`Live::appear`], [`Live::disappear`], [`Live::move_frame`],
//! [`restyle`], [`recolor`]) and calls [`Live::step`] on every frame with the view's
//! frame and style, which it writes the in-between values into: everything
//! that draws reads the current value without knowing about transitions,
//! and a change that arrives mid-animation starts from where the view is,
//! as UIKit's `beginFromCurrentState`.
//!
//! A text's color is not in its style but in its typeset runs, which a
//! new color replaces (laid out again, not measured again): while its
//! transition runs, the backend draws the text in [`Live::text_color`]
//! over the runs' colors, as it does an animated color, so no frame
//! typesets it again. iOS, whose other transitions are Core Animation's,
//! steps the same [`TextColor`] on a display link of its own.
//!
//! Appearing / disappearing views and keyframes do not touch the style:
//! they multiply the opacity ([`Live::opacity`]) and add a transform to the
//! style's ([`Live::extra`]), which the backend applies in its own matrix
//! type. Which views animate (navigation, reduced motion), the frame
//! callbacks and detaching a view that finished animating out stay in the
//! backends.

use std::sync::Arc;

use crate::{
    AttributedText, Bounds, BoxShadow, Color, Corners, Edges, KeyframeAnimation, Keyframes,
    LayoutCurve, LayoutProperty, LayoutTransition, Points, Transform, Transition, TransitionProps,
    ViewStyle,
    geometry::{Percentage, Point, Radians, Size, deg},
};

/// What animates on one view, and the values drawing reads.
#[non_exhaustive]
pub struct Live {
    /// A frame callback steps it.
    ticking: bool,
    /// A frame moving to its new place.
    frame: Option<FrameTrack>,
    /// Style values moving to the new style's.
    style: Option<StyleTrack>,
    /// A text's color moving to its new one.
    color: TextColor,
    /// Appearing or disappearing.
    presence: Option<Presence>,
    /// A keyframe animation.
    keyframes: Option<KeyframeRun>,
    /// The view was removed and stays only while it animates out.
    dying: bool,
    /// Opacity multiplier (appearing / disappearing, keyframes).
    opacity: f32,
    /// Transform added to the style's.
    extra: Extra,
}

impl Default for Live {
    fn default() -> Self {
        Live {
            ticking: false,
            frame: None,
            style: None,
            color: TextColor::default(),
            presence: None,
            keyframes: None,
            dying: false,
            opacity: 1.0,
            extra: Extra::NONE,
        }
    }
}

/// What one [`Live::step`] did.
#[non_exhaustive]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Step {
    /// The view finished animating out: the backend detaches it.
    pub removed: bool,
    /// Nothing is left to animate (or the view was removed): the frame
    /// callback stops ([`Live::ticking`] is false again).
    pub finished: bool,
    /// The frame's size changed.
    pub resized: bool,
    /// The style or text color transition moved (or ended).
    pub restyled: bool,
}

impl Live {
    /// The opacity multiplier of appearing, disappearing and keyframes.
    pub fn opacity(&self) -> f32 {
        self.opacity
    }

    /// The transform to add to the style's, if any.
    pub fn extra(&self) -> Option<Extra> {
        (self.extra != Extra::NONE).then_some(self.extra)
    }

    /// True while the view animates out after its removal: it is drawn but
    /// takes no pointer.
    pub fn dying(&self) -> bool {
        self.dying
    }

    /// The color a running text color transition draws the text in, over
    /// its runs' own: a text view draws all of it (decoration lines
    /// included) in this color while it is `Some`.
    pub fn text_color(&self) -> Option<Color> {
        self.color.value()
    }

    /// True when nothing animates.
    pub fn idle(&self) -> bool {
        self.frame.is_none()
            && self.style.is_none()
            && !self.color.running()
            && self.presence.is_none()
            && self.keyframes.is_none()
    }

    /// When what animates next ends (ms, the clock [`Live::step`] is
    /// given), or `now` when a change has to be stepped to start: what a
    /// surface that draws no frames (a hidden window) steps it at, so a
    /// view animating out is removed on time without frames. `None` while
    /// nothing animates, or only keyframes that repeat forever.
    pub fn deadline(&self, now: f64) -> Option<f64> {
        let keyframes = self.keyframes.as_ref().and_then(|run| {
            let n = run.animation.iterations?;
            let length = run.animation.delay.max(0.0) + n as f32 * run.animation.duration.max(0.0);
            Some(run.start.map_or(now, |start| start + length as f64))
        });
        [
            self.frame.as_ref().map(|t| t.timing.end(now)),
            self.style.as_ref().map(|t| t.timing.end(now)),
            self.color.0.as_ref().map(|t| t.timing.end(now)),
            self.presence.as_ref().map(|p| p.timing.end(now)),
            keyframes,
        ]
        .into_iter()
        .flatten()
        .reduce(f64::min)
        // A millisecond past it: a step there finds it ended whatever the
        // rounding of the time elapsed.
        .map(|t| t + 1.0)
    }

    /// The highest frame rate its animations need, in Hz: a keyframe
    /// animation's `animationFrameRate` while it is all that runs; `None`
    /// (the screen's highest) while a transition, a layout animation or an
    /// uncapped keyframe animation runs.
    pub fn frame_rate(&self) -> Option<f32> {
        let keyframes_alone = self.frame.is_none()
            && self.style.is_none()
            && !self.color.running()
            && self.presence.is_none();
        let run = self.keyframes.as_ref().filter(|_| keyframes_alone)?;
        crate::style::frame_rate(run.animation.frame_rate)
    }

    /// True while a frame callback steps it.
    pub fn ticking(&self) -> bool {
        self.ticking
    }

    /// Records whether a frame callback steps it (the backend sets it when
    /// it starts one; [`Live::step`] clears it when it finishes).
    pub fn set_ticking(&mut self, ticking: bool) {
        self.ticking = ticking;
    }

    /// The view is back (or moved) before its removal finished animating.
    pub fn revive(&mut self) {
        self.dying = false;
        self.presence = None;
        // The next step adds a keyframe animation's values again.
        self.opacity = 1.0;
        self.extra = Extra::NONE;
    }

    /// The view was inserted: it appears as `t` describes.
    pub fn appear(&mut self, t: LayoutTransition) {
        let presence = Presence {
            property: t.property,
            from: 0.0,
            to: 1.0,
            value: 0.0,
            timing: Timing::layout(&t),
        };
        self.opacity = 0.0;
        self.extra = presence.extra();
        self.presence = Some(presence);
    }

    /// The view was removed: it disappears as `t` describes, from where an
    /// appearance got to, and is [`Live::dying`] until done.
    pub fn disappear(&mut self, t: LayoutTransition) {
        let value = self.presence.as_ref().map_or(1.0, |p| p.value);
        self.dying = true;
        self.presence = Some(Presence {
            property: t.property,
            from: value,
            to: 0.0,
            value,
            timing: Timing::layout(&t),
        });
    }

    /// The frame a running layout animation is heading to, if any.
    pub fn frame_target(&self) -> Option<Bounds<Points>> {
        self.frame.as_ref().map(|t| t.to)
    }

    /// Stops a running layout animation (the new frame applies at once).
    pub fn stop_frame(&mut self) {
        self.frame = None;
    }

    /// The frame moves from `from` to `to` as `t` describes (the view shows
    /// `from` until the first step).
    pub fn move_frame(&mut self, from: Bounds<Points>, to: Bounds<Points>, t: LayoutTransition) {
        self.frame = Some(FrameTrack {
            from,
            to,
            timing: Timing::layout(&t),
        });
    }

    /// Stops a running style transition.
    pub fn stop_style(&mut self) {
        self.style = None;
    }

    /// Starts what [`restyle`] found.
    pub fn restyle(&mut self, restyle: Restyle) {
        self.style = restyle.track;
        if let Some(animation) = restyle.keyframes {
            self.keyframes = animation.map(|animation| KeyframeRun {
                animation,
                start: None,
            });
            if self.keyframes.is_none() {
                self.opacity = self.presence.as_ref().map_or(1.0, Presence::opacity);
                self.extra = self.presence.as_ref().map_or(Extra::NONE, Presence::extra);
            }
        }
    }

    /// Starts, keeps or stops a text color transition, as [`recolor`]
    /// found ([`TextColor::recolor`]).
    pub fn recolor(&mut self, recolor: Recolor) {
        self.color.recolor(recolor);
    }

    /// True if the view is removed and has not begun to animate out: a
    /// view deleted inside a deleted subtree leaves with its ancestor
    /// ([`Live::leave_with_ancestor`]) instead of fading on its own.
    pub fn leaving(&self) -> bool {
        self.dying
            && self
                .presence
                .as_ref()
                .is_some_and(|p| p.timing.start.is_none())
    }

    /// An ancestor animates out and takes the view with it.
    pub fn leave_with_ancestor(&mut self) {
        self.presence = None;
        self.dying = false;
    }

    /// One frame at `now` (ms): writes the animated frame and style into
    /// `frame` and `style` and updates [`Live::opacity`] and
    /// [`Live::extra`].
    pub fn step(
        &mut self,
        now: f64,
        frame: &mut Bounds<Points>,
        style: &mut Box<ViewStyle>,
    ) -> Step {
        let mut step = Step::default();

        if let Some(track) = &mut self.frame
            && let Some((p, done)) = track.timing.at(now)
        {
            let next = if done {
                track.to
            } else {
                lerp_rect(track.from, track.to, p)
            };
            step.resized = next.size.width.0 != frame.size.width.0
                || next.size.height.0 != frame.size.height.0;
            *frame = next;
            if done {
                self.frame = None;
            }
        }

        if let Some(track) = &mut self.style
            && let Some((p, done)) = track.timing.at(now)
        {
            step.restyled = true;
            if done {
                *style = std::mem::take(&mut track.to);
                self.style = None;
            } else {
                lerp_style(style, &track.from, &track.to, track.props, p);
            }
        }

        if self.color.step(now) {
            step.restyled = true;
        }

        let (mut opacity, mut extra) = (1.0, Extra::NONE);
        if let Some(presence) = &mut self.presence {
            let at = presence.timing.at(now);
            if let Some((p, done)) = at {
                presence.value = if done {
                    presence.to
                } else {
                    lerp(presence.from, presence.to, p)
                };
            }
            if at.is_some_and(|(_, done)| done) {
                step.removed = self.dying;
                self.presence = None;
            } else {
                opacity = presence.opacity();
                extra = presence.extra();
            }
        }

        if let Some(run) = &mut self.keyframes {
            let start = *run.start.get_or_insert(now);
            match keyframes_at(&run.animation, (now - start) as f32) {
                Some((o, e)) => {
                    opacity *= o;
                    extra = Extra {
                        rotate: extra.rotate + e.rotate,
                        scale: extra.scale * e.scale,
                        shift_y: extra.shift_y + e.shift_y,
                    };
                }
                None => self.keyframes = None,
            }
        }
        self.opacity = opacity;
        self.extra = extra;

        step.finished = step.removed || self.idle();
        if step.finished {
            self.ticking = false;
        }
        step
    }
}

/// What a style change starts, from [`restyle`] for [`Live::restyle`].
#[non_exhaustive]
pub struct Restyle {
    track: Option<StyleTrack>,
    /// The new keyframe animation, when it changed.
    keyframes: Option<Option<KeyframeAnimation>>,
}

/// A view's style changed from `old` to `style`: what it starts (a
/// transition of the values its `transition` names, a new keyframe
/// animation), or `None` when the new values apply at once (stop a running
/// transition with [`Live::stop_style`]). A transition writes the old
/// values into `style`, which shows them until the first step.
pub fn restyle(
    old: &ViewStyle,
    style: &mut Box<ViewStyle>,
    reduce_motion: bool,
) -> Option<Restyle> {
    // Keyframes restart only when the animation itself changes, as in CSS.
    let keyframes_changed = style.animation != old.animation;
    let transition = style.transition.filter(|t| {
        !reduce_motion
            && t.run_ms() + t.delay > 0.0
            && differs(old, style, t.properties)
            // A view's first style does not transition from the defaults.
            && *old != ViewStyle::default()
    });
    if transition.is_none() && !keyframes_changed {
        return None;
    }
    let keyframes = keyframes_changed.then(|| style.animation.filter(|_| !reduce_motion));
    let track = transition.map(|t| {
        let to = style.clone();
        lerp_style(style, old, &to, t.properties, 0.0);
        StyleTrack {
            from: Box::new(old.clone()),
            to,
            props: t.properties,
            timing: Timing::transition(&t),
        }
    });
    Some(Restyle { track, keyframes })
}

/// What a text's new content does to a transition of its color, from
/// [`recolor`] for [`Live::recolor`] or [`TextColor::recolor`].
#[non_exhaustive]
pub struct Recolor(Recoloring);

enum Recoloring {
    /// The color transitions.
    Start {
        from: Color,
        to: Color,
        timing: Timing,
    },
    /// The color is the same: a transition running to it goes on.
    Keep(Color),
    /// The new colors apply at once.
    Stop,
}

impl Default for Recolor {
    /// The new colors apply at once.
    fn default() -> Self {
        Recolor(Recoloring::Stop)
    }
}

impl Recolor {
    /// True if it starts a transition (the view needs a [`Live`] and a
    /// frame callback); otherwise it only matters to a [`Live`] the view
    /// already has.
    pub fn starts(&self) -> bool {
        matches!(self.0, Recoloring::Start { .. })
    }
}

/// A text's color moving to a new one, as [`recolor`] found: what
/// [`Live`] steps for the desktop backends, and what a backend that keeps
/// no [`Live`] (iOS) steps on its own frame clock. While it runs, the
/// text view draws all of its text in [`TextColor::value`] over its runs'
/// own colors, so no frame lays the text out again.
#[non_exhaustive]
#[derive(Default)]
pub struct TextColor(Option<ColorTrack>);

impl TextColor {
    /// The color to draw the whole text in (decoration lines included)
    /// while the transition runs; `None` draws the runs' own colors.
    pub fn value(&self) -> Option<Color> {
        self.0.as_ref().map(|c| c.value)
    }

    /// True while a transition runs: something steps it on every frame.
    pub fn running(&self) -> bool {
        self.0.is_some()
    }

    /// Starts, keeps or stops the transition. A new one starts from the
    /// color on screen, mid-transition included, as CSS reverses a
    /// transition from where it is.
    pub fn recolor(&mut self, recolor: Recolor) {
        match recolor.0 {
            Recoloring::Start { from, to, timing } => {
                let from = self.value().unwrap_or(from);
                self.0 = Some(ColorTrack {
                    from,
                    to,
                    value: from,
                    timing,
                });
            }
            Recoloring::Keep(to) => {
                if self.0.as_ref().is_some_and(|c| c.to != to) {
                    self.0 = None;
                }
            }
            Recoloring::Stop => self.0 = None,
        }
    }

    /// One frame at `now` (ms, any clock that only goes forward; the
    /// first frame starts the transition): true if [`TextColor::value`]
    /// changed, the text is drawn again. A transition that ends stops
    /// running, and the runs' own colors (the new ones) draw again.
    pub fn step(&mut self, now: f64) -> bool {
        let Some(track) = &mut self.0 else {
            return false;
        };
        let Some((p, done)) = track.timing.at(now) else {
            return false;
        };
        if done {
            self.0 = None;
        } else {
            track.value = lerp_color(track.from, track.to, p);
        }
        true
    }
}

/// A text view's content changed from `old` to `text`, its style being
/// `style`: whether its color transitions. It does when the style's
/// `transition` covers colors (`transition-colors`, `color`) and the text
/// is drawn in one color before and after
/// ([`AttributedText::uniform_color`]), as an element's `color`
/// transitions in CSS; a text of several colors takes its new ones at
/// once. The content may change with it: the color is drawn over the new
/// runs, which are not measured or typeset again.
pub fn recolor(
    old: &AttributedText,
    text: &AttributedText,
    style: &ViewStyle,
    reduce_motion: bool,
) -> Recolor {
    let transition = style.transition.filter(|t| {
        !reduce_motion && t.run_ms() + t.delay > 0.0 && t.properties.has(TransitionProps::COLORS)
    });
    // Most texts have no transition: their runs are not looked at.
    let Some((t, to)) = transition.and_then(|t| Some((t, text.uniform_color()?))) else {
        return Recolor::default();
    };
    Recolor(match old.uniform_color() {
        Some(from) if from == to => Recoloring::Keep(to),
        Some(from) => Recoloring::Start {
            from,
            to,
            timing: Timing::transition(&t),
        },
        None => Recoloring::Stop,
    })
}

/// A rotation, scale and vertical shift around the transform origin, which
/// appearing, disappearing and keyframes add to the style's transform.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Extra {
    /// Rotation.
    pub rotate: Radians,
    /// Uniform scale.
    pub scale: f32,
    /// Vertical shift, a fraction of the view's height.
    pub shift_y: Percentage,
}

impl Extra {
    /// No transform.
    pub const NONE: Extra = Extra {
        rotate: Radians(0.0),
        scale: 1.0,
        shift_y: Percentage(0.0),
    };
}

impl Default for Extra {
    fn default() -> Self {
        Extra::NONE
    }
}

/// An easing curve, from progress in time to progress in value.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Curve {
    Linear,
    /// Cubic Bézier `x1, y1, x2, y2`.
    Bezier([f32; 4]),
    /// A spring with this damping ratio that settles within the duration.
    Spring(f32),
    /// A spring's physics, over the time it settles in.
    Physical(crate::element::Spring),
}

impl Curve {
    fn of(curve: LayoutCurve) -> Curve {
        match curve {
            LayoutCurve::Linear => Curve::Linear,
            // UIKit's curves.
            LayoutCurve::EaseIn => Curve::Bezier([0.42, 0.0, 1.0, 1.0]),
            LayoutCurve::EaseOut => Curve::Bezier([0.0, 0.0, 0.58, 1.0]),
            LayoutCurve::EaseInEaseOut | LayoutCurve::Keyboard => {
                Curve::Bezier([0.42, 0.0, 0.58, 1.0])
            }
            LayoutCurve::FittedSpring { damping_ratio } => Curve::Spring(damping_ratio),
            LayoutCurve::Spring(spring) => Curve::Physical(spring),
            LayoutCurve::Bezier(points) => Curve::Bezier(points),
        }
    }

    fn at(self, x: f32) -> f32 {
        match self {
            Curve::Linear => x,
            Curve::Bezier(b) => cubic_bezier(b, x),
            Curve::Spring(damping) => spring(damping, x),
            Curve::Physical(spring) => spring.progress(x * spring.settle_ms()),
        }
    }
}

/// CSS `cubic-bezier(x1, y1, x2, y2)` at `x` in `0..=1`.
fn cubic_bezier([x1, y1, x2, y2]: [f32; 4], x: f32) -> f32 {
    if x <= 0.0 {
        return 0.0;
    }
    if x >= 1.0 {
        return 1.0;
    }
    // Polynomial coefficients of B(t) = ((a t + b) t + c) t.
    let (cx, cy) = (3.0 * x1, 3.0 * y1);
    let (bx, by) = (3.0 * (x2 - x1) - cx, 3.0 * (y2 - y1) - cy);
    let (ax, ay) = (1.0 - cx - bx, 1.0 - cy - by);
    let sample_x = |t: f32| ((ax * t + bx) * t + cx) * t;
    let slope_x = |t: f32| (3.0 * ax * t + 2.0 * bx) * t + cx;
    // Newton's method converges in a few steps on most curves; bisection
    // catches the flat ones.
    let mut t = x;
    let mut solved = false;
    for _ in 0..8 {
        let err = sample_x(t) - x;
        if err.abs() < 1e-6 {
            solved = true;
            break;
        }
        let d = slope_x(t);
        if d.abs() < 1e-6 {
            break;
        }
        t -= err / d;
    }
    if !solved || !(0.0..=1.0).contains(&t) {
        let (mut lo, mut hi) = (0.0f32, 1.0f32);
        t = x;
        for _ in 0..32 {
            let v = sample_x(t);
            if (v - x).abs() < 1e-6 {
                break;
            }
            if v < x {
                lo = t;
            } else {
                hi = t;
            }
            t = (lo + hi) / 2.0;
        }
    }
    ((ay * t + by) * t + cy) * t
}

/// A damped spring from 0 to 1 at `x` (the fraction of the duration), its
/// stiffness chosen so that it settles by the end, as UIKit's
/// `usingSpringWithDamping` fits a spring into the given duration.
fn spring(damping: f32, x: f32) -> f32 {
    if x <= 0.0 {
        return 0.0;
    }
    if x >= 1.0 {
        return 1.0;
    }
    // The envelope falls to 1/1000 by the end.
    const SETTLE: f32 = 6.907_755; // ln(1000)
    let zeta = damping.clamp(0.05, 1.0);
    if zeta > 0.999 {
        // Critically damped: (1 + w x) e^(-w x) reaches 1/1000 at w = 9.23.
        let w = 9.233;
        return 1.0 - (1.0 + w * x) * (-w * x).exp();
    }
    let w = SETTLE / zeta;
    let wd = w * (1.0 - zeta * zeta).sqrt();
    let envelope = (-zeta * w * x).exp();
    1.0 - envelope * ((wd * x).cos() + zeta * w / wd * (wd * x).sin())
}

/// When a change runs and how it eases.
#[derive(Debug, Clone, Copy)]
struct Timing {
    /// Frame time (ms) of the first step.
    start: Option<f64>,
    delay: f32,
    duration: f32,
    curve: Curve,
}

impl Timing {
    fn new(delay: f32, duration: f32, curve: Curve) -> Self {
        Timing {
            start: None,
            delay: delay.max(0.0),
            duration: duration.max(0.0),
            curve,
        }
    }

    fn layout(t: &LayoutTransition) -> Self {
        Timing::new(t.delay_ms, t.run_ms(), Curve::of(t.curve))
    }

    fn transition(t: &Transition) -> Self {
        let curve = match t.spring {
            Some(spring) => Curve::Physical(spring),
            None => Curve::Bezier(t.easing),
        };
        Timing::new(t.delay, t.run_ms(), curve)
    }

    /// When it ends (ms), `now` before its first step.
    fn end(&self, now: f64) -> f64 {
        self.start
            .map_or(now, |start| start + (self.delay + self.duration) as f64)
    }

    /// Eased progress at `now` (ms): `None` while delayed, then the value
    /// and whether it finished.
    fn at(&mut self, now: f64) -> Option<(f32, bool)> {
        let start = *self.start.get_or_insert(now);
        progress(self.curve, self.delay, self.duration, (now - start) as f32)
    }
}

/// Eased progress `elapsed` ms after a change began.
fn progress(curve: Curve, delay: f32, duration: f32, elapsed: f32) -> Option<(f32, bool)> {
    let t = elapsed - delay;
    if t < 0.0 {
        return None;
    }
    if duration <= 0.0 || t >= duration {
        return Some((1.0, true));
    }
    Some((curve.at(t / duration), false))
}

struct FrameTrack {
    from: Bounds<Points>,
    to: Bounds<Points>,
    timing: Timing,
}

struct StyleTrack {
    from: Box<ViewStyle>,
    to: Box<ViewStyle>,
    props: TransitionProps,
    timing: Timing,
}

struct ColorTrack {
    from: Color,
    to: Color,
    /// The color on screen.
    value: Color,
    timing: Timing,
}

struct Presence {
    property: LayoutProperty,
    /// Visibility at the start and end (0 hidden, 1 shown).
    from: f32,
    to: f32,
    /// The current visibility.
    value: f32,
    timing: Timing,
}

impl Presence {
    fn opacity(&self) -> f32 {
        match self.property {
            LayoutProperty::Opacity => self.value.clamp(0.0, 1.0),
            LayoutProperty::Scale => 1.0,
        }
    }

    fn extra(&self) -> Extra {
        match self.property {
            LayoutProperty::Opacity => Extra::NONE,
            LayoutProperty::Scale => Extra {
                // Not quite zero: a singular matrix cannot be inverted for
                // picking.
                scale: self.value.max(0.01),
                ..Extra::NONE
            },
        }
    }
}

struct KeyframeRun {
    animation: KeyframeAnimation,
    start: Option<f64>,
}

/// The opacity multiplier and extra transform of `animation`, `elapsed` ms
/// after it was set; `None` once a finite animation ended. During the delay
/// the view shows its own values, as CSS without `animation-fill-mode`.
fn keyframes_at(animation: &KeyframeAnimation, elapsed: f32) -> Option<(f32, Extra)> {
    let t = elapsed - animation.delay;
    if t < 0.0 {
        return Some((1.0, Extra::NONE));
    }
    let d = animation.duration;
    if d <= 0.0 || animation.iterations.is_some_and(|n| t >= n as f32 * d) {
        return None;
    }
    let frac = (t % d) / d;
    let ease = |x: f32| cubic_bezier(animation.easing, x);
    let mut extra = Extra::NONE;
    let mut opacity = 1.0;
    match animation.keyframes {
        Keyframes::Spin => extra.rotate = deg(360.0 * ease(frac)),
        Keyframes::Ping => {
            // 75%, 100% { transform: scale(2); opacity: 0 }
            let q = if frac < 0.75 { ease(frac / 0.75) } else { 1.0 };
            extra.scale = 1.0 + q;
            opacity = 1.0 - q;
        }
        Keyframes::Pulse => {
            // 50% { opacity: .5 }
            let q = if frac < 0.5 {
                ease(frac * 2.0)
            } else {
                1.0 - ease(frac * 2.0 - 1.0)
            };
            opacity = 1.0 - 0.5 * q;
        }
        Keyframes::Bounce => {
            // 0%, 100% { translateY(-25%) } eased in, 50% { none } eased
            // out; the animation's own easing does not apply.
            extra.shift_y = Percentage(if frac < 0.5 {
                -0.25 * (1.0 - cubic_bezier([0.8, 0.0, 1.0, 1.0], frac * 2.0))
            } else {
                -0.25 * cubic_bezier([0.0, 0.0, 0.2, 1.0], frac * 2.0 - 1.0)
            });
        }
    }
    Some((opacity, extra))
}

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

fn lerp_points(a: Points, b: Points, t: f32) -> Points {
    Points(lerp(a.0, b.0, t))
}

/// Interpolates colors in premultiplied RGBA, as CSS does, so that
/// transparent ends do not pass through black.
fn lerp_color(a: Color, b: Color, t: f32) -> Color {
    if a == b {
        return a;
    }
    let t = t.clamp(0.0, 1.0);
    let parts = |c: Color| {
        let (r, g, b, a) = c.to_f64();
        let a = a as f32;
        [r as f32 * a, g as f32 * a, b as f32 * a, a]
    };
    let (pa, pb) = (parts(a), parts(b));
    let p: [f32; 4] = std::array::from_fn(|i| lerp(pa[i], pb[i], t));
    let alpha = p[3];
    if alpha <= 0.0 {
        return Color::TRANSPARENT;
    }
    let channel = |v: f32| (v * 255.0).round().clamp(0.0, 255.0) as u8;
    Color::rgba(
        channel(p[0] / alpha),
        channel(p[1] / alpha),
        channel(p[2] / alpha),
        channel(alpha),
    )
}

/// Interpolates transform lists entry by entry when their kinds match (an
/// empty list stands for the identity of the other); `None` when they
/// cannot be interpolated and the new list applies at once.
fn lerp_transform(a: &Transform, b: &Transform, t: f32) -> Option<Transform> {
    let (ao, bo) = (a.ops(), b.ops());
    let same_kinds = ao.iter().map(|o| o.kind).eq(bo.iter().map(|o| o.kind));
    if !(ao.is_empty() || bo.is_empty() || same_kinds) {
        return None;
    }
    let kinds = if ao.is_empty() { bo } else { ao };
    let mut out = Transform::IDENTITY;
    for (i, op) in kinds.iter().enumerate() {
        let va = ao.get(i).map_or(op.kind.identity(), |o| o.value);
        let vb = bo.get(i).map_or(op.kind.identity(), |o| o.value);
        out.push(op.kind, lerp(va, vb, t));
    }
    Some(out)
}

/// A shadow that draws nothing, to interpolate against `s`.
fn none_like(s: &BoxShadow) -> BoxShadow {
    BoxShadow {
        offset_x: Points::ZERO,
        offset_y: Points::ZERO,
        blur: Points::ZERO,
        spread: Points::ZERO,
        color: Color::TRANSPARENT,
        inset: s.inset,
    }
}

/// Interpolates box shadow lists, the shorter padded with empty shadows
/// (CSS); `None` when an inset and an outer shadow meet.
fn lerp_box_shadows(a: &[BoxShadow], b: &[BoxShadow], t: f32) -> Option<Vec<BoxShadow>> {
    let n = a.len().max(b.len());
    let mut out = Vec::with_capacity(n);
    for i in 0..n {
        let (sa, sb) = match (a.get(i), b.get(i)) {
            (Some(x), Some(y)) => (*x, *y),
            (Some(x), None) => (*x, none_like(x)),
            (None, Some(y)) => (none_like(y), *y),
            (None, None) => unreachable!("i < the longer length"),
        };
        if sa.inset != sb.inset {
            return None;
        }
        let l = |a: Points, b: Points| Points(lerp(a.0, b.0, t));
        out.push(BoxShadow {
            offset_x: l(sa.offset_x, sb.offset_x),
            offset_y: l(sa.offset_y, sb.offset_y),
            blur: l(sa.blur, sb.blur).max(Points::ZERO),
            spread: l(sa.spread, sb.spread),
            color: lerp_color(sa.color, sb.color, t),
            inset: sa.inset,
        });
    }
    Some(out)
}

fn box_shadows(s: &ViewStyle) -> &[BoxShadow] {
    s.effects.as_deref().map_or(&[], |e| &e.box_shadows)
}

/// True if `a` and `b` differ in what `props` animates.
fn differs(a: &ViewStyle, b: &ViewStyle, props: TransitionProps) -> bool {
    (props.has(TransitionProps::COLORS)
        && (a.background_color != b.background_color
            || a.borders.colors != b.borders.colors
            || a.outline.color != b.outline.color
            || a.tint_color != b.tint_color))
        || (props.has(TransitionProps::OPACITY) && a.opacity != b.opacity)
        || (props.has(TransitionProps::TRANSFORM) && a.transform != b.transform)
        || (props.has(TransitionProps::SHADOW) && box_shadows(a) != box_shadows(b))
        // To or from `none` it changes at once, as in CSS.
        || (props.has(TransitionProps::CLIP_PATH)
            && a.clip_path().is_some()
            && b.clip_path().is_some()
            && a.clip_path() != b.clip_path())
        || (props.has(TransitionProps::SHAPE)
            && (a.border_radius != b.border_radius
                || a.corner_radius != b.corner_radius
                || a.borders.widths != b.borders.widths
                || a.outline.width != b.outline.width))
}

/// Writes the values between `from` and `to` that `props` animates into
/// `out` (a copy of `to`).
fn lerp_style(
    out: &mut ViewStyle,
    from: &ViewStyle,
    to: &ViewStyle,
    props: TransitionProps,
    t: f32,
) {
    if props.has(TransitionProps::COLORS) {
        out.background_color = lerp_color(from.background_color, to.background_color, t);
        out.borders.colors =
            std::array::from_fn(|i| lerp_color(from.borders.colors[i], to.borders.colors[i], t));
        out.outline.color = lerp_color(from.outline.color, to.outline.color, t);
        if let (Some(a), Some(b)) = (from.tint_color, to.tint_color) {
            out.tint_color = Some(lerp_color(a, b, t));
        }
    }
    if props.has(TransitionProps::OPACITY) {
        out.opacity = lerp(from.opacity, to.opacity, t).clamp(0.0, 1.0);
    }
    if props.has(TransitionProps::TRANSFORM)
        && let Some(transform) = lerp_transform(&from.transform, &to.transform, t)
    {
        out.transform = transform;
    }
    if props.has(TransitionProps::SHADOW) {
        let (sa, sb) = (box_shadows(from), box_shadows(to));
        if sa != sb
            && let Some(shadows) = lerp_box_shadows(sa, sb, t)
        {
            let mut effects = to.effects.as_deref().cloned().unwrap_or_default();
            effects.box_shadows = shadows;
            out.effects = Some(Arc::new(effects));
        }
    }
    if props.has(TransitionProps::CLIP_PATH)
        && let (Some(a), Some(b)) = (from.clip_path(), to.clip_path())
        && a != b
    {
        let mut effects = out.effects.as_deref().cloned().unwrap_or_default();
        effects.clip_path = Some(a.lerp(b, t));
        out.effects = Some(Arc::new(effects));
    }
    if props.has(TransitionProps::SHAPE) {
        out.border_radius = lerp_points(from.border_radius, to.border_radius, t).max(Points::ZERO);
        let (ca, cb) = (from.corner_radius.to_array(), to.corner_radius.to_array());
        out.corner_radius = Corners::from(std::array::from_fn(|i| match (ca[i], cb[i]) {
            (None, None) => None,
            (a, b) => Some(
                lerp_points(
                    a.unwrap_or(from.border_radius),
                    b.unwrap_or(to.border_radius),
                    t,
                )
                .max(Points::ZERO),
            ),
        }));
        let (wa, wb) = (from.borders.widths.to_array(), to.borders.widths.to_array());
        out.borders.widths = Edges::from(std::array::from_fn(|i| {
            lerp_points(wa[i], wb[i], t).max(Points::ZERO)
        }));
        out.outline.width = Points(lerp(from.outline.width.0, to.outline.width.0, t).max(0.0));
    }
}

fn lerp_rect(a: Bounds<Points>, b: Bounds<Points>, t: f32) -> Bounds<Points> {
    Bounds {
        origin: Point {
            x: Points(lerp(a.origin.x.0, b.origin.x.0, t)),
            y: Points(lerp(a.origin.y.0, b.origin.y.0, t)),
        },
        size: Size {
            width: Points(lerp(a.size.width.0, b.size.width.0, t).max(0.0)),
            height: Points(lerp(a.size.height.0, b.size.height.0, t).max(0.0)),
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        LayoutAnimation, TransformKind,
        element::Spring,
        geometry::{point, size},
    };

    fn close(a: f32, b: f32) -> bool {
        (a - b).abs() < 1e-3
    }

    #[test]
    fn bezier_matches_css() {
        let ease = [0.25, 0.1, 0.25, 1.0];
        assert_eq!(cubic_bezier(ease, 0.0), 0.0);
        assert_eq!(cubic_bezier(ease, 1.0), 1.0);
        // Reference values of CSS `ease`.
        assert!(
            close(cubic_bezier(ease, 0.5), 0.8024),
            "{}",
            cubic_bezier(ease, 0.5)
        );
        assert!(
            close(cubic_bezier(ease, 0.25), 0.4094),
            "{}",
            cubic_bezier(ease, 0.25)
        );
        assert!(close(cubic_bezier([0.0, 0.0, 1.0, 1.0], 0.37), 0.37));
        let in_out = [0.42, 0.0, 0.58, 1.0];
        let mut last = 0.0;
        for i in 1..=100 {
            let v = cubic_bezier(in_out, i as f32 / 100.0);
            assert!(v >= last, "monotonic");
            last = v;
        }
        assert!(close(cubic_bezier(in_out, 0.5), 0.5));
        // A flat start (x1 = 1) still solves.
        assert!(cubic_bezier([0.8, 0.0, 1.0, 1.0], 0.5) < 0.3);
    }

    #[test]
    fn spring_settles_and_overshoots() {
        assert_eq!(spring(0.4, 0.0), 0.0);
        assert_eq!(spring(0.4, 1.0), 1.0);
        let max = (1..100)
            .map(|i| spring(0.4, i as f32 / 100.0))
            .fold(0.0, f32::max);
        assert!(max > 1.1, "a loose spring overshoots: {max}");
        assert!((spring(0.4, 0.99) - 1.0).abs() < 0.01);
        // A critically damped spring does not overshoot.
        assert!((1..100).all(|i| spring(1.0, i as f32 / 100.0) <= 1.0));
        assert!((spring(1.0, 0.98) - 1.0).abs() < 0.01);
    }

    /// `spring` released at rest at 0 toward 1, stepped by semi-implicit
    /// Euler at 10 µs: where it is after each of `steps` milliseconds.
    fn integrate(spring: Spring, steps: usize) -> Vec<f64> {
        let (k, c, m) = (
            f64::from(spring.stiffness),
            f64::from(spring.damping),
            f64::from(spring.mass),
        );
        let (mut x, mut v) = (0.0_f64, 0.0_f64);
        let mut out = Vec::new();
        for _ in 0..steps {
            for _ in 0..100 {
                v += (-k * (x - 1.0) - c * v) / m * 1e-5;
                x += v * 1e-5;
            }
            out.push(x);
        }
        out
    }

    /// A spring of these physics: stiffness, damping coefficient, mass.
    fn physics(stiffness: f32, damping: f32, mass: f32) -> Spring {
        Spring {
            stiffness,
            damping,
            mass,
            ..Spring::default()
        }
    }

    /// M3 Expressive's fast spatial spring (stiffness 800, damping ratio
    /// 0.6, mass 1), its damping as a coefficient: 2 · 0.6 · √800.
    const FAST_SPATIAL: Spring = Spring {
        stiffness: 800.0,
        damping: 33.941_124,
        mass: 1.0,
        velocity: None,
        frame_rate: None,
    };

    #[test]
    fn a_physical_spring_follows_its_physics() {
        let critical = physics(400.0, 40.0, 1.0);
        let overdamped = physics(100.0, 40.0, 2.0);
        for spring in [FAST_SPATIAL, critical, overdamped] {
            assert_eq!(spring.progress(0.0), 0.0, "{spring:?}");
            for (ms, expected) in integrate(spring, 600).into_iter().enumerate() {
                let found = f64::from(spring.progress((ms + 1) as f32));
                assert!(
                    (found - expected).abs() < 1e-3,
                    "{spring:?} at {ms} ms: {found} vs {expected}"
                );
            }
        }
        // Underdamped, it overshoots; critically damped or overdamped, it does not.
        assert!((1..400).any(|ms| FAST_SPATIAL.progress(ms as f32) > 1.0));
        for spring in [critical, overdamped] {
            assert!(
                (1..2000).all(|ms| spring.progress(ms as f32) <= 1.0),
                "{spring:?}"
            );
        }
    }

    #[test]
    fn a_physical_spring_settles_within_a_thousandth_by_its_settling_time() {
        // ln(1000) / (0.6 · √800) s.
        assert!(
            (FAST_SPATIAL.settle_ms() - 407.03).abs() < 0.1,
            "{}",
            FAST_SPATIAL.settle_ms()
        );
        let springs = [
            FAST_SPATIAL,
            physics(400.0, 40.0, 1.0),
            physics(100.0, 40.0, 2.0),
            physics(1400.0, 67.35, 1.0),
        ];
        for spring in springs {
            let settle = spring.settle_ms();
            let zeta = spring.damping / (2.0 * (spring.stiffness * spring.mass).sqrt());
            // Underdamped, its decay is 1/1000 there: the swing is within 1/1000 of 1/√(1-ζ²).
            let bound = if zeta < 0.999 {
                1e-3 / (1.0 - zeta * zeta).sqrt()
            } else {
                1e-3
            };
            for ms in [settle, settle + 50.0, settle * 2.0] {
                let off = (spring.progress(ms) - 1.0).abs();
                assert!(off <= bound * 1.01, "{spring:?} at {ms} ms: {off}");
            }
            // Not long before: it is still more than a thousandth away somewhere.
            let earlier =
                (0..100).any(|i| (spring.progress(settle * 0.7 + i as f32) - 1.0).abs() > 1e-3);
            assert!(earlier, "{spring:?} settled long before {settle} ms");
        }
    }

    #[test]
    fn a_spring_that_never_settles_is_there_at_once() {
        for spring in [
            physics(800.0, 0.0, 1.0),
            physics(0.0, 30.0, 1.0),
            physics(800.0, 30.0, 0.0),
            physics(f32::NAN, 30.0, 1.0),
            physics(f32::INFINITY, 30.0, 1.0),
        ] {
            assert_eq!(spring.progress(10.0), 1.0, "{spring:?}");
            assert_eq!(spring.settle_ms(), 0.0, "{spring:?}");
            let mut t = Timing::layout(&LayoutTransition::spring(spring));
            assert_eq!(t.at(0.0), Some((1.0, true)), "{spring:?}");
        }
    }

    #[test]
    fn a_layout_spring_moves_by_its_physics_and_ends_when_it_settles() {
        let transition = LayoutTransition::spring(FAST_SPATIAL);
        assert_eq!(transition.curve, LayoutCurve::Spring(FAST_SPATIAL));
        assert_eq!(transition.duration_ms, FAST_SPATIAL.settle_ms());
        assert_eq!(transition.delay_ms, 0.0);
        let mut t = Timing::layout(&transition);
        assert_eq!(t.at(1000.0), Some((0.0, false)));
        for ms in [16.0_f32, 100.0, 250.0, 400.0] {
            let (value, done) = t.at(1000.0 + f64::from(ms)).unwrap();
            assert!(
                close(value, FAST_SPATIAL.progress(ms)) && !done,
                "{ms} ms: {value}"
            );
        }
        assert_eq!(
            t.at(1000.0 + f64::from(transition.duration_ms)),
            Some((1.0, true))
        );
    }

    #[test]
    fn a_layout_spring_times_itself_whatever_its_duration() {
        let settle = FAST_SPATIAL.settle_ms();
        for duration in [100.0, 2000.0] {
            let transition = LayoutTransition::new(LayoutCurve::Spring(FAST_SPATIAL), duration);
            assert_eq!(transition.run_ms(), settle);
            let mut t = Timing::layout(&transition);
            t.at(0.0);
            assert!(
                close(t.at(100.0).unwrap().0, FAST_SPATIAL.progress(100.0)),
                "{duration}"
            );
            assert_eq!(t.at(f64::from(settle)), Some((1.0, true)), "{duration}");
        }
        // Other curves keep their duration.
        assert_eq!(
            LayoutTransition::new(LayoutCurve::Linear, 100.0).run_ms(),
            100.0
        );
    }

    #[test]
    fn a_spring_is_made_as_gpui_base_makes_one() {
        // `Spring::new(response)`: one undamped swing in `response`, critically damped.
        let spring = Spring::new(280.0);
        let omega = std::f32::consts::TAU / 0.28;
        assert!(close(spring.stiffness, omega * omega) && close(spring.mass, 1.0));
        assert!(close(spring.damping, 2.0 * omega));
        assert!((1..2000).all(|ms| spring.progress(ms as f32) <= 1.0));
        // `with_damping(0.85)`: ln 1000 / (0.85 · 2π / 0.28 s), what `Tabs` waited by hand.
        let move_ = spring.damping_ratio(0.85);
        assert!(
            (move_.settle_ms() - 362.2).abs() < 0.1,
            "{}",
            move_.settle_ms()
        );
        assert!((1..400).any(|ms| move_.progress(ms as f32) > 1.0));
        // From a stiffness token, at another mass: the ratio holds.
        let mut heavy = Spring::from_stiffness(800.0);
        heavy.mass = 2.0;
        let heavy = heavy.damping_ratio(0.6);
        assert!(close(heavy.damping / (2.0 * (800.0_f32 * 2.0).sqrt()), 0.6));
        assert!(close(
            Spring::from_stiffness(800.0).damping_ratio(0.6).damping,
            FAST_SPATIAL.damping
        ));
        // A critically damped 180 ms response settles where `Collapsible` waited by hand.
        assert!(
            (Spring::new(180.0).settle_ms() - 264.5).abs() < 0.5,
            "{}",
            Spring::new(180.0).settle_ms()
        );
    }

    #[test]
    fn progress_waits_for_delay() {
        assert_eq!(progress(Curve::Linear, 100.0, 200.0, 50.0), None);
        assert_eq!(
            progress(Curve::Linear, 100.0, 200.0, 200.0),
            Some((0.5, false))
        );
        assert_eq!(
            progress(Curve::Linear, 100.0, 200.0, 300.0),
            Some((1.0, true))
        );
        assert_eq!(progress(Curve::Linear, 0.0, 0.0, 0.0), Some((1.0, true)));
    }

    /// A view scaled from `from` to `to` with `easing` on its transforms:
    /// the scales it shows every 10 ms until the transition ends.
    fn scales(
        easing: [f32; 4],
        spring: Option<crate::element::Spring>,
        from: f32,
        to: f32,
    ) -> Vec<f32> {
        let styled = |scale: f32| {
            let mut transform = Transform::IDENTITY;
            let _ = transform.push(crate::transform::TransformKind::Scale, scale);
            ViewStyle {
                transform,
                transition: Some(Transition {
                    properties: TransitionProps(TransitionProps::TRANSFORM),
                    duration: 200.0,
                    delay: 0.0,
                    easing,
                    spring,
                }),
                ..ViewStyle::default()
            }
        };
        let old = styled(from);
        let mut style = Box::new(styled(to));
        let mut live = Live::default();
        live.restyle(restyle(&old, &mut style, false).expect("it transitions"));
        let mut frame = Bounds::default();
        let mut out = Vec::new();
        for i in 0..200 {
            let step = live.step(f64::from(i) * 10.0, &mut frame, &mut style);
            out.push(style.transform.ops()[0].value);
            if step.finished {
                break;
            }
        }
        out
    }

    #[test]
    fn a_clip_path_opens_out_of_a_corner() {
        use crate::{ClipInset, geometry::percentage};
        let clipped = |clip: Option<ClipInset>, properties: u8| {
            let mut style = transitioning(properties);
            style.effects = crate::effects::shared(crate::Effects {
                clip_path: clip,
                ..Default::default()
            });
            style
        };
        let shut = ClipInset::new()
            .bottom(percentage(1.0))
            .left(percentage(1.0))
            .rounded(Points(12.0));
        let open = ClipInset::new().rounded(Points(12.0));
        let old = clipped(Some(shut), TransitionProps::CLIP_PATH);
        let mut style = Box::new(clipped(Some(open), TransitionProps::CLIP_PATH));
        let mut live = Live::default();
        live.restyle(restyle(&old, &mut style, false).expect("it transitions"));
        // The old shape shows until the first frame, then each edge moves
        // on its own (linear, 150 ms): from the top right corner.
        assert_eq!(style.clip_path(), Some(&shut));
        let mut frame = Bounds::default();
        live.step(1000.0, &mut frame, &mut style);
        live.step(1075.0, &mut frame, &mut style);
        let half = style.clip_path().copied().unwrap();
        assert_eq!(half.fractions.left, percentage(0.5));
        assert_eq!(half.fractions.bottom, percentage(0.5));
        assert_eq!(half.fractions.top, percentage(0.0));
        let (rect, radii) = half.resolve(size(Points(200.0), Points(100.0)));
        assert_eq!(
            rect,
            Bounds::new(
                point(Points(100.0), Points(0.0)),
                size(Points(100.0), Points(50.0))
            )
        );
        assert_eq!(radii.top_right, Points(12.0));
        let step = live.step(1200.0, &mut frame, &mut style);
        assert!(step.finished);
        assert_eq!(style.clip_path(), Some(&open));

        // Not named, or to and from `none`, it changes at once, as in CSS.
        let mut style = Box::new(clipped(Some(open), TransitionProps::SHAPE));
        assert!(
            restyle(
                &clipped(Some(shut), TransitionProps::SHAPE),
                &mut style,
                false
            )
            .is_none()
        );
        let mut style = Box::new(clipped(Some(open), TransitionProps::ALL));
        let mut old = clipped(None, TransitionProps::ALL);
        old.opacity = 0.5;
        let restyled = restyle(&old, &mut style, false).expect("the opacity transitions");
        assert_eq!(style.clip_path(), Some(&open));
        drop(restyled);
    }

    #[test]
    fn a_style_transition_runs_on_a_spring() {
        let spring = crate::element::Spring {
            stiffness: 620.0,
            damping: 36.0,
            ..crate::element::Spring::default()
        };
        let shown = scales(Transition::EASE, Some(spring), 0.95, 1.0);
        // It passes its target (by 3.7% of the travel) and settles on it, in
        // the time the spring takes, not the transition's 200 ms.
        let peak = shown.iter().copied().fold(f32::MIN, f32::max);
        assert!(peak > 1.001 && peak < 1.003, "{peak}");
        assert_eq!(*shown.last().unwrap(), 1.0);
        let ms = (shown.len() - 1) * 10;
        assert!((380..=390).contains(&ms), "{ms}");
        // Its exit waits as long.
        let t = Transition {
            properties: TransitionProps(TransitionProps::ALL),
            duration: 200.0,
            delay: 20.0,
            easing: Transition::EASE,
            spring: Some(spring),
        };
        assert!((t.run_ms() - spring.settle_ms()).abs() < f32::EPSILON);
    }

    #[test]
    fn a_bezier_past_one_overshoots() {
        let shown = scales([0.3, 1.25, 0.6, 1.0], None, 0.95, 1.0);
        let peak = shown.iter().copied().fold(f32::MIN, f32::max);
        assert!(peak > 1.0, "{peak}");
        assert_eq!(*shown.last().unwrap(), 1.0);
        assert_eq!(shown.len(), 21);
    }

    #[test]
    fn presets_time_as_configured() {
        let mut t = Timing::layout(&LayoutAnimation::EASE_IN_EASE_OUT.update.unwrap());
        assert_eq!(t.at(1000.0), Some((0.0, false)));
        assert!(close(t.at(1150.0).unwrap().0, 0.5));
        assert_eq!(t.at(1300.0), Some((1.0, true)));
        let mut t = Timing::layout(&LayoutAnimation::LINEAR.create.unwrap());
        t.at(0.0);
        assert!(close(t.at(125.0).unwrap().0, 0.25));
        assert_eq!(t.at(500.0), Some((1.0, true)));
        let spring = LayoutAnimation::SPRING;
        let mut t = Timing::layout(&spring.update.unwrap());
        t.at(0.0);
        // The frame overshoots at some point before settling at 700 ms.
        let over = (1..70).any(|i| t.at(i as f64 * 10.0).unwrap().0 > 1.0);
        assert!(over);
        assert_eq!(t.at(700.0), Some((1.0, true)));
        assert_eq!(spring.create.unwrap().property, LayoutProperty::Opacity);
        assert_eq!(Curve::of(spring.delete.unwrap().curve), Curve::Linear);
    }

    #[test]
    fn rects_interpolate_and_never_go_negative() {
        let a = Bounds {
            origin: Point {
                x: Points(0.0),
                y: Points(10.0),
            },
            size: Size {
                width: Points(100.0),
                height: Points(40.0),
            },
        };
        let b = Bounds {
            origin: Point {
                x: Points(50.0),
                y: Points(20.0),
            },
            size: Size {
                width: Points(0.0),
                height: Points(80.0),
            },
        };
        let r = lerp_rect(a, b, 0.5);
        assert_eq!(
            (r.origin.x.0, r.origin.y.0, r.size.width.0, r.size.height.0),
            (25.0, 15.0, 50.0, 60.0)
        );
        // A spring past its end does not make a negative size.
        assert_eq!(lerp_rect(a, b, 1.2).size.width.0, 0.0);
    }

    #[test]
    fn presence_values() {
        let p = Presence {
            property: LayoutProperty::Scale,
            from: 0.0,
            to: 1.0,
            value: 0.0,
            timing: Timing::new(0.0, 100.0, Curve::Linear),
        };
        assert_eq!(p.opacity(), 1.0);
        assert_eq!(p.extra().scale, 0.01);
        let p = Presence {
            property: LayoutProperty::Opacity,
            value: 0.4,
            ..p
        };
        assert_eq!(p.opacity(), 0.4);
        assert_eq!(p.extra(), Extra::NONE);
    }

    #[test]
    fn colors_interpolate_premultiplied() {
        let red = Color::rgba(255, 0, 0, 255);
        let blue = Color::rgba(0, 0, 255, 255);
        assert_eq!(lerp_color(red, blue, 0.5), Color::rgba(128, 0, 128, 255));
        // From transparent the color stays red while it fades in.
        assert_eq!(
            lerp_color(Color::TRANSPARENT, red, 0.5),
            Color::rgba(255, 0, 0, 128)
        );
        assert_eq!(lerp_color(red, blue, 1.0), blue);
    }

    #[test]
    fn transforms_interpolate_by_position() {
        let mut a = Transform::IDENTITY;
        a.push(TransformKind::TranslateX, 10.0);
        a.push(TransformKind::Scale, 1.0);
        let mut b = Transform::IDENTITY;
        b.push(TransformKind::TranslateX, 30.0);
        b.push(TransformKind::Scale, 2.0);
        let m = lerp_transform(&a, &b, 0.5).unwrap();
        assert_eq!(m.ops()[0].value, 20.0);
        assert_eq!(m.ops()[1].value, 1.5);
        // From none: each entry's identity.
        let m = lerp_transform(&Transform::IDENTITY, &b, 0.5).unwrap();
        assert_eq!(m.ops()[0].value, 15.0);
        assert_eq!(m.ops()[1].value, 1.5);
        let mut c = Transform::IDENTITY;
        c.push(TransformKind::Rotate, 90.0);
        assert!(lerp_transform(&a, &c, 0.5).is_none());
    }

    #[test]
    fn style_lerp_touches_only_its_groups() {
        let from = ViewStyle {
            opacity: 0.0,
            background_color: Color::rgba(0, 0, 0, 255),
            ..ViewStyle::default()
        };
        let to = ViewStyle {
            opacity: 1.0,
            background_color: Color::rgba(255, 255, 255, 255),
            border_radius: Points(10.0),
            ..ViewStyle::default()
        };
        let mut out = to.clone();
        lerp_style(
            &mut out,
            &from,
            &to,
            TransitionProps(TransitionProps::OPACITY),
            0.5,
        );
        assert_eq!(out.opacity, 0.5);
        assert_eq!(out.background_color, to.background_color);
        assert_eq!(out.border_radius, Points(10.0));
        assert!(differs(
            &from,
            &to,
            TransitionProps(TransitionProps::COLORS)
        ));
        assert!(!differs(&from, &to, TransitionProps(0)));
    }

    #[test]
    fn box_shadows_pad_with_none() {
        let s = BoxShadow {
            offset_x: Points(0.0),
            offset_y: Points(10.0),
            blur: Points(20.0),
            spread: Points(0.0),
            color: Color::rgba(0, 0, 0, 100),
            inset: false,
        };
        let out = lerp_box_shadows(&[], &[s], 0.5).unwrap();
        assert_eq!(out[0].offset_y, Points(5.0));
        assert_eq!(out[0].blur, Points(10.0));
        assert_eq!(out[0].color, Color::rgba(0, 0, 0, 50));
        let inset = BoxShadow { inset: true, ..s };
        assert!(lerp_box_shadows(&[inset], &[s], 0.5).is_none());
    }

    #[test]
    fn keyframes() {
        let anim = |keyframes, iterations| KeyframeAnimation {
            keyframes,
            duration: 1000.0,
            delay: 0.0,
            easing: [0.0, 0.0, 1.0, 1.0],
            iterations,
            frame_rate: None,
        };
        let spin = anim(Keyframes::Spin, None);
        assert!(close(
            keyframes_at(&spin, 250.0).unwrap().1.rotate.to_degrees(),
            90.0
        ));
        assert!(close(
            keyframes_at(&spin, 1250.0).unwrap().1.rotate.to_degrees(),
            90.0
        ));
        let ping = anim(Keyframes::Ping, Some(1));
        let (o, e) = keyframes_at(&ping, 375.0).unwrap();
        assert!(close(o, 0.5) && close(e.scale, 1.5));
        assert!(close(keyframes_at(&ping, 900.0).unwrap().0, 0.0));
        assert!(keyframes_at(&ping, 1000.0).is_none());
        let pulse = anim(Keyframes::Pulse, None);
        assert!(close(keyframes_at(&pulse, 500.0).unwrap().0, 0.5));
        assert!(close(keyframes_at(&pulse, 0.0).unwrap().0, 1.0));
        let bounce = anim(Keyframes::Bounce, None);
        assert!(close(
            keyframes_at(&bounce, 0.0).unwrap().1.shift_y.0,
            -0.25
        ));
        assert!(close(
            keyframes_at(&bounce, 500.0).unwrap().1.shift_y.0,
            0.0
        ));
        // Delayed: the view's own values.
        let delayed = KeyframeAnimation {
            delay: 300.0,
            ..spin
        };
        assert_eq!(keyframes_at(&delayed, 100.0), Some((1.0, Extra::NONE)));
    }

    #[test]
    fn keyframes_alone_ask_for_their_frame_rate() {
        let spin = KeyframeAnimation::new(Keyframes::Spin);
        let restyle = |animation| Restyle {
            track: None,
            keyframes: Some(animation),
        };
        let mut live = Live::default();
        assert_eq!(live.frame_rate(), None);
        live.restyle(restyle(Some(spin)));
        assert_eq!(live.frame_rate(), None);
        live.restyle(restyle(Some(spin.frame_rate(30.0))));
        assert_eq!(live.frame_rate(), Some(30.0));
        // With a layout animation running beside it: the screen's highest.
        live.appear(LayoutTransition::new(LayoutCurve::Linear, 300.0));
        assert_eq!(live.frame_rate(), None);
    }

    #[test]
    fn a_view_appears_and_disappears() {
        let t = LayoutAnimation::LINEAR.create.unwrap();
        let mut live = Live::default();
        live.appear(t);
        assert_eq!(live.opacity(), 0.0);
        let (mut frame, mut style) = (Bounds::default(), Box::default());
        live.step(0.0, &mut frame, &mut style);
        let step = live.step(250.0, &mut frame, &mut style);
        assert!(!step.finished && close(live.opacity(), 0.5));
        live.disappear(t);
        assert!(live.dying() && live.leaving());
        live.step(1000.0, &mut frame, &mut style);
        assert!(close(live.opacity(), 0.5));
        let step = live.step(2000.0, &mut frame, &mut style);
        assert!(step.removed && step.finished && !live.ticking());
    }

    #[test]
    fn a_view_animating_out_is_removed_at_its_deadline() {
        let t = LayoutAnimation::LINEAR.create.unwrap();
        let mut live = Live::default();
        let (mut frame, mut style) = (Bounds::default(), Box::default());
        assert_eq!(live.deadline(0.0), None);
        live.appear(t);
        live.step(0.0, &mut frame, &mut style);
        live.disappear(t);
        // Not started: step now, which starts it.
        assert_eq!(live.deadline(100.0), Some(101.0));
        live.step(100.0, &mut frame, &mut style);
        let end = live.deadline(100.0).expect("it animates out");
        assert!(close(end as f32, 100.0 + t.duration_ms + 1.0), "{end}");
        let step = live.step(end, &mut frame, &mut style);
        assert!(step.removed && step.finished);
        assert_eq!(live.deadline(end), None);
    }

    #[test]
    fn keyframes_that_repeat_forever_give_no_deadline() {
        let mut live = Live::default();
        let spin = |iterations| KeyframeAnimation {
            keyframes: Keyframes::Spin,
            duration: 1000.0,
            delay: 0.0,
            easing: [0.0, 0.0, 1.0, 1.0],
            iterations,
            frame_rate: None,
        };
        live.keyframes = Some(KeyframeRun {
            animation: spin(None),
            start: Some(0.0),
        });
        assert_eq!(live.deadline(10.0), None);
        live.keyframes = Some(KeyframeRun {
            animation: spin(Some(2)),
            start: Some(0.0),
        });
        assert_eq!(live.deadline(10.0), Some(2001.0));
    }

    fn text(colors: &[Color]) -> AttributedText {
        let mut text = AttributedText::default();
        for &color in colors {
            let style = crate::ResolvedTextStyle {
                color,
                ..Default::default()
            };
            text.push("Tab", style);
        }
        text
    }

    fn transitioning(properties: u8) -> ViewStyle {
        ViewStyle {
            transition: Some(crate::Transition {
                properties: TransitionProps(properties),
                duration: 150.0,
                delay: 0.0,
                easing: [0.0, 0.0, 1.0, 1.0],
                spring: None,
            }),
            ..ViewStyle::default()
        }
    }

    #[test]
    fn a_text_color_transitions() {
        let (red, blue) = (Color::rgba(255, 0, 0, 255), Color::rgba(0, 0, 255, 255));
        // `transition-colors duration-150`, linear.
        let style = transitioning(TransitionProps::COLORS);
        let recolor = recolor(&text(&[red]), &text(&[blue]), &style, false);
        assert!(recolor.starts());
        let mut live = Live::default();
        live.recolor(recolor);
        // The old color shows until the first frame.
        assert_eq!(live.text_color(), Some(red));
        let (mut frame, mut shown) = (Bounds::default(), Box::default());
        live.step(1000.0, &mut frame, &mut shown);
        assert_eq!(live.text_color(), Some(red));
        let step = live.step(1060.0, &mut frame, &mut shown);
        assert!(step.restyled && !step.finished);
        assert_eq!(live.text_color(), Some(Color::rgba(153, 0, 102, 255)));
        // Back to red mid-way: from the color on screen.
        live.recolor(super::recolor(
            &text(&[blue]),
            &text(&[red]),
            &transitioning(TransitionProps::ALL),
            false,
        ));
        assert_eq!(live.text_color(), Some(Color::rgba(153, 0, 102, 255)));
        live.step(2000.0, &mut frame, &mut shown);
        live.step(2060.0, &mut frame, &mut shown);
        assert_eq!(live.text_color(), Some(Color::rgba(194, 0, 61, 255)));
        // New content in the color it is heading to: it goes on.
        let mut longer = text(&[red]);
        longer.push(" 2", longer.spans[0].style);
        live.recolor(super::recolor(
            &text(&[red]),
            &longer,
            &transitioning(TransitionProps::COLORS),
            false,
        ));
        assert!(live.text_color().is_some());
        // Done: the runs' own color draws again.
        let step = live.step(2150.0, &mut frame, &mut shown);
        assert!(step.restyled && step.finished && live.idle());
        assert_eq!(live.text_color(), None);
    }

    #[test]
    fn a_text_color_jumps_without_a_colors_transition() {
        let (red, blue) = (Color::rgba(255, 0, 0, 255), Color::rgba(0, 0, 255, 255));
        let colors = transitioning(TransitionProps::COLORS);
        let starts = |old: &[Color], new: &[Color], style: &ViewStyle, reduce: bool| {
            recolor(&text(old), &text(new), style, reduce).starts()
        };
        assert!(!starts(&[red], &[blue], &ViewStyle::default(), false));
        assert!(!starts(
            &[red],
            &[blue],
            &transitioning(TransitionProps::OPACITY),
            false
        ));
        assert!(!starts(&[red], &[blue], &colors, true));
        assert!(!starts(&[red], &[red], &colors, false));
        // Several colors take their new ones at once.
        assert!(!starts(&[red, blue], &[blue], &colors, false));
        assert!(!starts(&[red], &[blue, red], &colors, false));
        assert!(!starts(&[], &[blue], &colors, false));
        // Decoration lines of another color are another color.
        let mut underlined = text(&[blue]);
        underlined.spans[0].style.decoration.underline = true;
        assert_eq!(underlined.uniform_color(), Some(blue));
        underlined.spans[0].style.decoration_color = Some(red);
        assert_eq!(underlined.uniform_color(), None);
        assert!(!recolor(&text(&[red]), &underlined, &colors, false).starts());
        // A stopped transition leaves no color behind.
        let mut live = Live::default();
        live.recolor(recolor(&text(&[red]), &text(&[blue]), &colors, false));
        live.recolor(recolor(&text(&[blue]), &text(&[red, blue]), &colors, false));
        assert!(live.idle() && live.text_color().is_none());
    }

    #[test]
    fn a_text_color_steps_without_a_live() {
        // iOS steps a `TextColor` on a display link of its own.
        let (red, blue) = (Color::rgba(255, 0, 0, 255), Color::rgba(0, 0, 255, 255));
        let mut style = transitioning(TransitionProps::COLORS);
        style.transition.as_mut().unwrap().delay = 50.0;
        let mut color = TextColor::default();
        assert!(!color.running() && !color.step(0.0));
        color.recolor(recolor(&text(&[red]), &text(&[blue]), &style, false));
        assert!(color.running());
        // Delayed: the old color shows, nothing to draw again.
        assert!(!color.step(1000.0) && !color.step(1040.0));
        assert_eq!(color.value(), Some(red));
        assert!(color.step(1110.0));
        assert_eq!(color.value(), Some(Color::rgba(153, 0, 102, 255)));
        // The end draws once more, in the runs' own color.
        assert!(color.step(1200.0));
        assert!(!color.running() && color.value().is_none());
        assert!(!color.step(1216.0));
    }
}