nsh-core 0.8.1

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
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
//! Native animation values for Rust components (TS: `createAnimatedValue`,
//! `Animated.spring`, `interpolate`): nodes of the platform's animation
//! graph that styles, drags, scroll offsets and drawings are bound to, so
//! they move on the UI thread with no engine work per frame. Composed
//! animations ([`Animation`], TS: `Animated.sequence` and co.) run there
//! too, step after step.
//!
//! Ids are odd (JS gives its own nodes, animations and composites even
//! ones), so the graph, which indexes nodes by id, stays dense.
//!
//! [`AnimatedValue`] and [`AnimatedNode`] are `Copy` handles: the reactive
//! owner current when one is made (the component, a region, a row) keeps
//! its node, and releases it when it is disposed. Used after that, a
//! handle does nothing (its derivations are gone as well). What binds a
//! node keeps it while bound ([`LiveNode`]: an element's styles, drags and
//! scroll offsets, a drawing, a composed animation, a derived node's
//! inputs), so a binding in a region that outlives the handle's owner
//! goes on moving, and an animation running on it goes on running.
//! Listeners and tasks run under the owner that made them, so what they
//! make is that owner's too; deriving a node again under an owner that
//! has a handle of it returns that handle ([`Derived`]), so code run over
//! and over adds nothing. Made with no owner at all (outside any
//! component), a handle keeps its node as long as the surface, as a
//! signal made there lives as long as the graph.

use std::{
    cell::Cell,
    fmt,
    rc::{Rc, Weak},
};

use super::{
    AdaptiveColor,
    reactive::{Kept, Owner},
    task::{Action, Answer, Executor},
};
use crate::animation::{
    AnimationId, AnimationOp, Composite, Driver, Easing, Extrapolate, Keyframe, KeyframeTiming,
    MathOp, MotionChannel, MotionSpec, Operand, Output, StaggerFrom,
};

/// A node of the graph, released when the last of what holds it goes
/// (the owner of its handles, its bindings, the nodes derived from it).
pub(crate) struct Node {
    id: crate::animation::NodeId,
    executor: Weak<Executor>,
    /// The nodes it derives from, alive while it is: a chain such as
    /// `v.mul(TAU).sub(1.0)` keeps no handle of its middle node.
    _inputs: Vec<Rc<Node>>,
}

impl Node {
    fn new(
        executor: &Rc<Executor>,
        op: impl FnOnce(crate::animation::NodeId) -> AnimationOp,
        inputs: Vec<Rc<Node>>,
    ) -> Rc<Self> {
        let id = executor.next_animation_id();
        executor.act(Action::Animation(op(id)));
        Rc::new(Self {
            id,
            executor: Rc::downgrade(executor),
            _inputs: inputs,
        })
    }

    fn act(&self, op: AnimationOp) {
        if let Some(executor) = self.executor.upgrade() {
            executor.act(Action::Animation(op));
        }
    }
}

impl Drop for Node {
    fn drop(&mut self) {
        self.act(AnimationOp::Release { node: self.id });
    }
}

/// `op` (a node-making operation) making node `id`.
fn with_node(mut op: AnimationOp, id: crate::animation::NodeId) -> AnimationOp {
    match &mut op {
        AnimationOp::CreateValue { node, .. }
        | AnimationOp::CreateInterpolate { node, .. }
        | AnimationOp::CreateDiffClamp { node, .. }
        | AnimationOp::CreateMath { node, .. } => *node = id,
        _ => {}
    }
    op
}

/// Derived nodes by what made them ([`DerivedKey`]), while alive, with the
/// handles of each that owners keep: deriving a node again under an owner
/// that has a handle of it returns that handle, so doing it over and over
/// (in a listener, a binding run again) adds nothing.
///
/// Kept by a hash of their keys, so a derive looks at the few of the same
/// hash, not at every derived node: deriving a graph's nodes one by one
/// costs time that grows with their number, not with its square.
#[derive(Default)]
pub(crate) struct Derived {
    by_hash: rustc_hash::FxHashMap<u64, Vec<DerivedNode>>,
    /// Nodes added since dead ones were last swept out.
    added: usize,
    /// How many were live then.
    live: usize,
}

/// What makes a derived node: its operation (node id 0) and, for colors
/// that follow the appearance, the dark ones (the operation has the light
/// ones, whichever appearance is current), so interpolations sharing their
/// light colors are not one node, and neither are a constant one and an
/// adaptive one.
#[derive(Clone, PartialEq)]
struct DerivedKey {
    op: AnimationOp,
    dark: Option<Output>,
}

struct DerivedNode {
    key: DerivedKey,
    node: Weak<Node>,
    /// The live handles of it, by the owner keeping each.
    handles: Vec<(Owner, AnimatedNode)>,
}

impl DerivedKey {
    /// A hash of the key, alike for equal keys: the operation's kind, its
    /// inputs and its numbers (by their bits, both zeros as one).
    fn hash(&self) -> u64 {
        use std::hash::{Hash, Hasher};
        fn number(h: &mut rustc_hash::FxHasher, v: f32) {
            (if v == 0.0 { 0 } else { v.to_bits() }).hash(h);
        }
        fn operand(h: &mut rustc_hash::FxHasher, o: &Operand) {
            match *o {
                Operand::Node(n) => n.hash(h),
                Operand::Const(c) => number(h, c),
            }
        }
        let mut h = rustc_hash::FxHasher::default();
        std::mem::discriminant(&self.op).hash(&mut h);
        match &self.op {
            AnimationOp::CreateInterpolate {
                input,
                input_range,
                output,
                ..
            } => {
                input.hash(&mut h);
                input_range.iter().for_each(|&v| number(&mut h, v));
                match output {
                    Output::Numbers(v) => v.iter().for_each(|&v| number(&mut h, v)),
                    Output::Colors(v) => v.hash(&mut h),
                }
            }
            AnimationOp::CreateMath { a, b, .. } => {
                operand(&mut h, a);
                operand(&mut h, b);
            }
            AnimationOp::CreateDiffClamp {
                input, min, max, ..
            } => {
                input.hash(&mut h);
                operand(&mut h, min);
                operand(&mut h, max);
            }
            _ => {}
        }
        h.finish()
    }
}

impl Derived {
    /// The live node `key` made.
    fn entry(&mut self, key: &DerivedKey) -> Option<&mut DerivedNode> {
        let same = self.by_hash.get_mut(&key.hash())?;
        same.retain(|d| d.node.strong_count() > 0);
        same.iter_mut().find(|d| d.key == *key)
    }

    /// Adds `node`, newly made. Dead nodes are swept out once as many were
    /// added as lived at the last sweep, so sweeping costs each addition a
    /// share of one pass.
    fn add(&mut self, node: DerivedNode) {
        self.added += 1;
        if self.added > self.live.max(64) {
            self.by_hash.retain(|_, same| {
                same.retain(|d| d.node.strong_count() > 0);
                !same.is_empty()
            });
            self.live = self.by_hash.values().map(Vec::len).sum();
            self.added = 0;
        }
        self.by_hash.entry(node.key.hash()).or_default().push(node);
    }
}

/// A value of the graph: [`AnimatedValue`] or [`AnimatedNode`], to bind
/// (`Styled::bind_opacity`) or derive from.
pub trait Animated {
    /// The node.
    fn animated_node(&self) -> AnimatedNode;
}

/// A node of the graph held while something is bound to it (an element's
/// style or gesture, a drawing, a composed animation): it outlives the
/// owner of the handle it came from for as long as it is held.
#[derive(Clone)]
pub(crate) struct LiveNode(Rc<Node>);

impl LiveNode {
    pub(crate) fn id(&self) -> crate::animation::NodeId {
        self.0.id
    }

    fn act(&self, op: AnimationOp) {
        self.0.act(op);
    }

    fn executor(&self) -> Option<Rc<Executor>> {
        self.0.executor.upgrade()
    }
}

impl PartialEq for LiveNode {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl fmt::Debug for LiveNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("LiveNode").field(&self.id()).finish()
    }
}

/// A node derived from values (an interpolation, arithmetic): bound like a
/// value, moving when they move. A `Copy` handle, kept by the owner it was
/// made under (see the module's docs).
#[derive(Clone, Copy)]
pub struct AnimatedNode {
    node: Kept<Node>,
    /// The node's id, for what names it (styles, equality) without
    /// reaching it.
    id: crate::animation::NodeId,
}

impl AnimatedNode {
    /// Keeps `node` in the current owner.
    fn keep(node: Rc<Node>) -> Self {
        let id = node.id;
        Self {
            node: Kept::new(node),
            id,
        }
    }

    /// A handle of no node (made from a handle whose owner is gone).
    fn gone() -> Self {
        Self {
            node: Kept::gone(),
            id: 0,
        }
    }

    pub(crate) fn id(&self) -> crate::animation::NodeId {
        self.id
    }

    /// The node, while the owner of the handle lives: what a binding
    /// holds.
    pub(crate) fn live(&self) -> Option<LiveNode> {
        self.node.get().map(LiveNode)
    }

    /// Sends `op` to the graph while the node is live (queuing it reaches
    /// only the executor, never the reactive graph).
    fn act(&self, op: impl FnOnce(crate::animation::NodeId) -> AnimationOp) {
        let id = self.id;
        self.node.with(|node| node.act(op(id)));
    }

    /// Where the node's operations go, while it is live.
    fn executor(&self) -> Option<Rc<Executor>> {
        self.node.with(|node| node.executor.upgrade()).flatten()
    }

    /// The node `key` makes from this one: the live one made by the same
    /// key if there is one (a region or a row made again derives it again
    /// and gets the same node, so its bindings stay as they are), through
    /// the handle the current owner keeps of it (made the first time), and
    /// whether that handle is new. A new node is made by `now` if given (the
    /// current appearance's colors), else by the key's operation. Of a node
    /// whose owner is gone (or with an operand whose owner is gone): no
    /// node.
    fn derive(
        &self,
        key: DerivedKey,
        now: Option<AnimationOp>,
        others: &[Option<AnimatedNode>],
    ) -> (AnimatedNode, bool) {
        let Some(node) = self.live() else {
            return (Self::gone(), false);
        };
        let mut live = Vec::new();
        for other in others.iter().flatten() {
            match other.live() {
                Some(other) => live.push(other),
                None => return (Self::gone(), false),
            }
        }
        let Some(executor) = node.executor() else {
            // The surface is gone: a node nothing reads.
            return (*self, false);
        };
        let owner = Owner::current();
        let mut derived = executor.derived();
        if let Some(entry) = derived.entry(&key) {
            entry.handles.retain(|(_, h)| h.node.is_live());
            if let Some(&(_, handle)) = entry.handles.iter().find(|(o, _)| *o == owner) {
                return (handle, false);
            }
            let Some(node) = entry.node.upgrade() else {
                unreachable!("entries are of live nodes");
            };
            let handle = Self::keep(node);
            entry.handles.push((owner, handle));
            return (handle, true);
        }
        drop(derived);
        let mut inputs = vec![node.0];
        inputs.extend(live.into_iter().map(|o| o.0));
        let op = now.unwrap_or_else(|| key.op.clone());
        let node = Node::new(&executor, |id| with_node(op, id), inputs);
        let weak = Rc::downgrade(&node);
        let handle = Self::keep(node);
        executor.derived().add(DerivedNode {
            key,
            node: weak,
            handles: vec![(owner, handle)],
        });
        (handle, true)
    }

    /// Maps the value through `input` breakpoints (ascending) to numbers,
    /// clamped at both ends: `x.interpolate(&[0.0, 300.0], &[1.0, 0.0])`.
    pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
        self.interpolate_with(
            input,
            Output::Numbers(output.to_vec()),
            Interpolation::default(),
        )
    }

    /// Maps the value to colors (`backgroundColor` bindings). Theme colors
    /// (`AdaptiveColor`s) follow the appearance: when it changes, the node
    /// takes the other appearance's colors in place, its bindings as they
    /// are.
    pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
        &self,
        input: &[f32],
        colors: &[C],
    ) -> AnimatedNode {
        let colors: Rc<[AdaptiveColor]> = colors.iter().map(|&c| c.into()).collect();
        let pick = {
            let colors = colors.clone();
            move |dark: bool| {
                Output::Colors(
                    colors
                        .iter()
                        .map(|c| crate::style::Color::from(if dark { c.dark } else { c.light }).0)
                        .collect(),
                )
            }
        };
        if colors.iter().all(|c| c.light == c.dark) {
            return self.interpolate_with(input, pick(false), Interpolation::default());
        }
        let (node, new) = self.interpolate_derived(
            input,
            pick(false),
            Some(pick(true)),
            Interpolation::default(),
        );
        // The appearance's colors from now on; the effect holds the node
        // while it lives (it goes with the owner that keeps the handle,
        // which has one already when the handle is not new).
        let Some(held) = node.live().filter(|_| new) else {
            return node;
        };
        let first = Cell::new(true);
        super::reactive::render_effect(move || {
            let output = pick(super::dark());
            if !first.replace(false) {
                held.act(AnimationOp::SetOutput {
                    node: held.id(),
                    output,
                });
            }
        });
        node
    }

    /// [`Self::interpolate`] with any output, extrapolation on each side
    /// and curve (TS: `interpolate({ extrapolateLeft, extrapolateRight,
    /// easing })`).
    pub fn interpolate_with(
        &self,
        input: &[f32],
        output: Output,
        interpolation: Interpolation,
    ) -> AnimatedNode {
        self.interpolate_derived(input, output, None, interpolation)
            .0
    }

    /// [`Self::interpolate_with`] to `output`, or, with `dark`, to the
    /// current appearance's of `output` (light) and `dark`; and whether its
    /// handle is new.
    fn interpolate_derived(
        &self,
        input: &[f32],
        output: Output,
        dark: Option<Output>,
        interpolation: Interpolation,
    ) -> (AnimatedNode, bool) {
        let op = |output| AnimationOp::CreateInterpolate {
            node: 0,
            input: self.id(),
            input_range: input.to_vec(),
            output,
            extrapolate_left: interpolation.extrapolate_left,
            extrapolate_right: interpolation.extrapolate_right,
            easing: interpolation.easing,
        };
        let now = dark
            .clone()
            .filter(|_| super::untracked(super::dark))
            .map(op);
        self.derive(
            DerivedKey {
                op: op(output),
                dark,
            },
            now,
            &[],
        )
    }

    fn math(&self, op: MathOp, other: AnimationOperand) -> AnimatedNode {
        let a = Operand::Node(self.id());
        let b = other.operand;
        let op = AnimationOp::CreateMath { node: 0, op, a, b };
        self.derive(DerivedKey { op, dark: None }, None, &[other.node])
            .0
    }

    /// The sum with `other`.
    pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.math(MathOp::Add, other.into())
    }

    /// The difference with `other`.
    pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.math(MathOp::Sub, other.into())
    }

    /// The product with `other`.
    pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.math(MathOp::Mul, other.into())
    }

    /// The quotient by `other`.
    pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.math(MathOp::Div, other.into())
    }

    /// The remainder by `other`.
    pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.math(MathOp::Mod, other.into())
    }

    /// Follows the value's changes but stays within `min..=max` (a header
    /// hiding as content scrolls up). Each bound is a number or another
    /// animated value, read at each evaluation: a range that changes while
    /// dragging clamps at its current bounds.
    pub fn diff_clamp(
        &self,
        min: impl Into<AnimationOperand>,
        max: impl Into<AnimationOperand>,
    ) -> AnimatedNode {
        self.diff_clamp_with(min, max, DiffClamp::default())
    }

    /// [`Self::diff_clamp`] with options: [`DiffClamp::snapping`] settles at
    /// the nearer bound when the scroll view the value follows comes to rest
    /// (TS: `diffClamp(min, max, { snap: true })`).
    pub fn diff_clamp_with(
        &self,
        min: impl Into<AnimationOperand>,
        max: impl Into<AnimationOperand>,
        options: DiffClamp,
    ) -> AnimatedNode {
        let (min, max) = (min.into(), max.into());
        let op = AnimationOp::CreateDiffClamp {
            node: 0,
            input: self.id(),
            min: min.operand,
            max: max.operand,
            snap: options.snap,
        };
        self.derive(DerivedKey { op, dark: None }, None, &[min.node, max.node])
            .0
    }
}

/// Options of [`AnimatedNode::diff_clamp_with`] (TS: `diffClamp`'s third
/// argument). By default it only follows its input.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct DiffClamp {
    /// When the scroll view the value follows comes to rest between the
    /// bounds, it settles at the nearer one in 200 ms, easing out: a
    /// floating bar shows or hides fully. It settles at `max` only once
    /// the value reached `max`, so a page scrolled less than the bar's
    /// height shows the whole bar.
    pub snap: bool,
}

impl DiffClamp {
    /// Settles at the nearer bound when its scroll view rests.
    pub const fn snapping() -> Self {
        Self { snap: true }
    }
}

impl Animated for AnimatedNode {
    fn animated_node(&self) -> AnimatedNode {
        *self
    }
}

impl PartialEq for AnimatedNode {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl fmt::Debug for AnimatedNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("AnimatedNode").field(&self.id()).finish()
    }
}

/// An operand of arithmetic on nodes: a number or another node.
#[derive(Debug, Clone)]
pub struct AnimationOperand {
    operand: Operand,
    /// The node, which what derives from it holds.
    node: Option<AnimatedNode>,
}

impl From<f32> for AnimationOperand {
    fn from(n: f32) -> Self {
        Self {
            operand: Operand::Const(n),
            node: None,
        }
    }
}

impl<A: Animated> From<&A> for AnimationOperand {
    fn from(a: &A) -> Self {
        let node = a.animated_node();
        Self {
            operand: Operand::Node(node.id()),
            node: Some(node),
        }
    }
}

/// How [`AnimatedNode::interpolate_with`] maps: what it does outside the
/// input range on each side, and the curve within each segment (TS:
/// `extrapolateLeft`, `extrapolateRight`, `easing`). By default it clamps
/// on both sides, linearly.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Interpolation {
    /// Below the first breakpoint.
    pub extrapolate_left: Extrapolate,
    /// Above the last breakpoint.
    pub extrapolate_right: Extrapolate,
    /// The curve within each segment.
    pub easing: Easing,
}

impl Interpolation {
    /// `extrapolate` on both sides, linearly (TS: `extrapolate`).
    pub const fn extrapolate(extrapolate: Extrapolate) -> Self {
        Self {
            extrapolate_left: extrapolate,
            extrapolate_right: extrapolate,
            easing: Easing::Linear,
        }
    }
}

impl Default for Interpolation {
    fn default() -> Self {
        Self::extrapolate(Extrapolate::Clamp)
    }
}

/// A settable, animatable value (made with
/// [`super::animated_value`]): set it, animate it, bind it, derive
/// from it. A `Copy` handle, kept by the owner it was made under: copies
/// are the same value, closures share it as they share a signal; used
/// after the owner is gone, it does nothing (see the module's docs).
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct AnimatedValue(AnimatedNode);

/// How a spring moves (TS's defaults: stiffness 170, damping 26, mass 1):
/// an animated value's ([`AnimatedValue::spring`]) and a layout
/// animation's ([`LayoutTransition::spring`](crate::LayoutTransition::spring)).
///
/// Made as `gpui-base`'s `Spring` is, from how long it takes and how much it
/// overshoots ([`Spring::new`], [`Spring::damping_ratio`]), or from a
/// stiffness, as Material 3's motion tokens give it
/// ([`Spring::from_stiffness`]); its fields are the physics either way.
///
/// ```
/// use nsh_core::element::Spring;
///
/// // `gpui-component`'s `spring_move`: a 280 ms response, a little springy.
/// let spring = Spring::new(280.0).damping_ratio(0.85);
/// assert!((spring.settle_ms() - 362.2).abs() < 0.1);
/// // Material 3 Expressive's fast spatial spring.
/// let spring = Spring::from_stiffness(800.0).damping_ratio(0.6);
/// assert!((spring.settle_ms() - 407.0).abs() < 0.1);
/// ```
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Spring {
    /// Stiffness `k`.
    pub stiffness: f32,
    /// Damping coefficient `c` (not a ratio: the ratio is `c / (2 √(k m))`,
    /// [`Spring::damping_ratio`] sets it).
    pub damping: f32,
    /// Mass `m`.
    pub mass: f32,
    /// The velocity it starts with (per second); `None` keeps the current
    /// one.
    pub velocity: Option<f32>,
    /// The highest frame rate it needs, in Hz (TS's `frameRate`); `None`:
    /// the screen's highest ([`Driver::frame_rate`]).
    pub frame_rate: Option<f32>,
}

impl Default for Spring {
    fn default() -> Self {
        Self {
            stiffness: 170.0,
            damping: 26.0,
            mass: 1.0,
            velocity: None,
            frame_rate: None,
        }
    }
}

/// How a timing animation moves (TS's defaults: 300 ms, ease in-out, no
/// delay).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Timing {
    /// How long it takes, in milliseconds.
    pub duration_ms: f32,
    /// The curve.
    pub easing: Easing,
    /// How long it waits before it starts, in milliseconds.
    pub delay_ms: f32,
    /// The highest frame rate it needs, in Hz (TS's `frameRate`); `None`:
    /// the screen's highest ([`Driver::frame_rate`]).
    pub frame_rate: Option<f32>,
}

impl Timing {
    /// `duration_ms` along `easing`, with no delay.
    pub const fn new(duration_ms: f32, easing: Easing) -> Self {
        Self {
            duration_ms,
            easing,
            delay_ms: 0.0,
            frame_rate: None,
        }
    }

    /// Needing at most `hz` frames per second (a slow fade: 30).
    pub const fn frame_rate(mut self, hz: f32) -> Self {
        self.frame_rate = Some(hz);
        self
    }

    fn driver(self, to: f32) -> Driver {
        Driver::Timing {
            to,
            duration_ms: self.duration_ms,
            easing: self.easing,
            delay_ms: self.delay_ms,
            frame_rate: self.frame_rate,
        }
    }
}

impl Default for Timing {
    fn default() -> Self {
        Self::new(300.0, Easing::EaseInOut)
    }
}

impl Spring {
    /// `gpui-base`'s `Spring::new(response)`: a mass of 1 that would swing
    /// once in `response_ms` undamped, critically damped (no overshoot).
    /// The response is the scale the motion is felt at, not when it stops
    /// ([`Spring::settle_ms`]).
    pub fn new(response_ms: f32) -> Self {
        let omega = std::f32::consts::TAU / (response_ms / 1000.0);
        Self {
            stiffness: omega * omega,
            damping: 2.0 * omega,
            mass: 1.0,
            velocity: None,
            frame_rate: None,
        }
    }

    /// A mass of 1 on a spring of `stiffness`, critically damped: a design
    /// system's stiffness token, its damping ratio set with
    /// [`Spring::damping_ratio`].
    pub fn from_stiffness(stiffness: f32) -> Self {
        Self {
            stiffness,
            damping: 2.0 * stiffness.max(0.0).sqrt(),
            mass: 1.0,
            velocity: None,
            frame_rate: None,
        }
    }

    /// Damped at `ratio` (`gpui-base`'s `with_damping`): 1 does not
    /// overshoot, below 1 it passes its target and comes back, above 1 it
    /// approaches slowly. Sets [`Spring::damping`] from the stiffness and
    /// mass it has, so set those first.
    pub fn damping_ratio(mut self, ratio: f32) -> Self {
        self.damping = 2.0 * ratio * (self.stiffness * self.mass).max(0.0).sqrt();
        self
    }

    /// How far it has gone, from 0 to 1, `ms` milliseconds after it was
    /// released at rest: the damped oscillator's closed form, past 1 when
    /// it is underdamped. A spring that never settles (no damping, or a
    /// stiffness or mass that is not positive) is at 1 at once.
    pub fn progress(self, ms: f32) -> f32 {
        let Some((zeta, omega)) = self.oscillator() else {
            return 1.0;
        };
        if ms <= 0.0 {
            return 0.0;
        }
        let t = ms / 1000.0;
        if (zeta - 1.0).abs() < CRITICAL {
            return 1.0 - (1.0 + omega * t) * (-omega * t).exp();
        }
        if zeta < 1.0 {
            let decay = zeta * omega;
            let wd = omega * (1.0 - zeta * zeta).sqrt();
            return 1.0 - (-decay * t).exp() * ((wd * t).cos() + decay / wd * (wd * t).sin());
        }
        let root = omega * (zeta * zeta - 1.0).sqrt();
        let (slow, fast) = (zeta * omega - root, zeta * omega + root);
        1.0 - (fast * (-slow * t).exp() - slow * (-fast * t).exp()) / (fast - slow)
    }

    /// How long it takes, in milliseconds, released at rest, to stay within
    /// a thousandth of its travel: how long a layout animation on it lasts.
    /// 0 for a spring that never settles.
    pub fn settle_ms(self) -> f32 {
        let Some((zeta, omega)) = self.oscillator() else {
            return 0.0;
        };
        let seconds = if (zeta - 1.0).abs() < CRITICAL {
            // (1 + ω t) e^(-ω t) falls to 1/1000 at ω t = 9.233.
            9.233 / omega
        } else if zeta < 1.0 {
            SETTLE / (zeta * omega)
        } else {
            // The slow root's term, whose weight is above 1, outlasts the fast one's.
            let root = (zeta * zeta - 1.0).sqrt();
            let weight = (zeta + root) / (2.0 * root);
            (SETTLE + weight.ln()) / (omega * (zeta - root))
        };
        seconds * 1000.0
    }

    /// The damping ratio and the natural angular frequency (radians per
    /// second); `None` when it never settles.
    fn oscillator(self) -> Option<(f32, f32)> {
        let Spring {
            stiffness,
            damping,
            mass,
            ..
        } = self;
        if !(stiffness > 0.0 && mass > 0.0 && damping > 0.0)
            || !(stiffness.is_finite() && mass.is_finite() && damping.is_finite())
        {
            return None;
        }
        let zeta = damping / (2.0 * (stiffness * mass).sqrt());
        Some((zeta, (stiffness / mass).sqrt()))
    }

    /// Needing at most `hz` frames per second (a small, slow spring: 60).
    pub const fn frame_rate(mut self, hz: f32) -> Self {
        self.frame_rate = Some(hz);
        self
    }

    fn driver(self, to: f32) -> Driver {
        Driver::Spring {
            to,
            stiffness: self.stiffness,
            damping: self.damping,
            mass: self.mass,
            velocity: self.velocity,
            frame_rate: self.frame_rate,
        }
    }
}

/// ln(1000): a decay of e^(-x) falls to a thousandth at this x.
const SETTLE: f32 = 6.907_755;

/// How close to 1 a damping ratio is taken as critical, where the
/// underdamped and overdamped forms divide by almost 0.
const CRITICAL: f32 = 1e-3;

/// The values `driver` moves a value through from `from`, one per frame at
/// `fps` (1 to 1000), until it ends: the exact curve the graph runs.
fn sample(driver: Driver, from: f32, fps: f32) -> Vec<f32> {
    let step = 1.0 / f64::from(fps.clamp(1.0, 1000.0));
    crate::animation::sample_driver(driver, from, step, crate::animation::MAX_SAMPLES)
}

/// The values a spring moves a value through from `from` to `to`, one per
/// frame at `fps` (60 on most screens) until it rests (TS:
/// `Animated.sampleSpring`): its curve, to draw it. At most
/// [`crate::animation::MAX_SAMPLES`].
pub fn sample_spring(from: f32, to: f32, spring: Spring, fps: f32) -> Vec<f32> {
    sample(spring.driver(to), from, fps)
}

/// The values a decay ([`AnimatedValue::decay`]) moves a value through from
/// `from` at `velocity` (per second), one per frame at `fps` until it
/// stops (TS: `Animated.sampleDecay`). At most
/// [`crate::animation::MAX_SAMPLES`].
pub fn sample_decay(from: f32, velocity: f32, deceleration: f32, fps: f32) -> Vec<f32> {
    sample(
        Driver::Decay {
            velocity: Some(velocity),
            deceleration,
            clamp: None,
            bounce: 0.0,
            frame_rate: None,
        },
        from,
        fps,
    )
}

/// Like [`sample_decay`], within `min..=max` ([`AnimatedValue::decay_within`]:
/// it stops at a bound, or bounces back keeping `bounce` of its speed).
pub fn sample_decay_within(
    from: f32,
    velocity: f32,
    deceleration: f32,
    (min, max): (f32, f32),
    bounce: f32,
    fps: f32,
) -> Vec<f32> {
    sample(
        Driver::Decay {
            velocity: Some(velocity),
            deceleration,
            clamp: Some((min, max)),
            bounce,
            frame_rate: None,
        },
        from,
        fps,
    )
}

/// The end of an animation: `true` when it reached its end, `false` when
/// it was stopped or replaced (or never ran: its value's owner was gone).
/// The animation runs either way: await this in a task to follow it up, or
/// drop it.
#[derive(Debug)]
pub struct AnimationEnd(Answer<bool>);

impl std::future::IntoFuture for AnimationEnd {
    type Output = bool;
    type IntoFuture = Answer<bool>;

    fn into_future(self) -> Answer<bool> {
        self.0
    }
}

impl AnimatedValue {
    pub(crate) fn new(executor: &Rc<Executor>, value: f32) -> Self {
        Self(AnimatedNode::keep(Node::new(
            executor,
            |node| AnimationOp::CreateValue { node, value },
            Vec::new(),
        )))
    }

    /// The node, to derive from.
    pub fn node(&self) -> &AnimatedNode {
        &self.0
    }

    /// Sets the value at once, stopping its animation.
    pub fn set(&self, value: f32) {
        self.0.act(|node| AnimationOp::Set { node, value });
    }

    /// Stops its animation where it is ([`Self::value`] then reads where
    /// that is; TS: `stop()`'s promise).
    pub fn stop(&self) {
        self.0.act(|node| AnimationOp::Stop { node });
    }

    /// Its value now, read on the UI thread where it moves (TS:
    /// `getValue()`): after the changes queued before it (a [`Self::stop`],
    /// a [`Self::set`]). Await it in a task. Once its owner is gone, it
    /// never comes.
    pub fn value(&self) -> Answer<f32> {
        let (answer, slot) = Answer::new();
        if let Some(executor) = self.0.executor() {
            executor.act(Action::ReadValue {
                node: self.0.id(),
                value: slot,
            });
        }
        answer
    }

    fn start(&self, driver: Driver) -> AnimationEnd {
        let (end, slot) = Answer::new();
        let end = AnimationEnd(end);
        match self.0.executor() {
            Some(executor) => {
                let animation = executor.next_animation_id();
                executor.act(Action::Animate {
                    op: AnimationOp::Start {
                        node: self.0.id(),
                        animation,
                        driver,
                    },
                    animation,
                    end: slot,
                });
            }
            // Its owner (or the surface) is gone: it ends at once, unfinished.
            None => slot.borrow_mut().deliver(false),
        }
        end
    }

    /// Plays `frames` as CSS keyframes play (TS: `keyframes(frames,
    /// options)`): each segment with its easing, `timing.iterations` times
    /// in `timing.direction`.
    pub fn keyframes(
        &self,
        frames: impl IntoIterator<Item = Keyframe>,
        timing: KeyframeTiming,
    ) -> AnimationEnd {
        Animation::keyframes(self, frames, timing).start()
    }

    /// Springs to `to`.
    pub fn spring(&self, to: f32, spring: Spring) -> AnimationEnd {
        self.start(spring.driver(to))
    }

    /// Moves to `to` in `ms` milliseconds along `easing`.
    pub fn timing(&self, to: f32, ms: f32, easing: Easing) -> AnimationEnd {
        self.timing_with(to, Timing::new(ms, easing))
    }

    /// Moves to `to` as `timing` says, after its delay.
    pub fn timing_with(&self, to: f32, timing: Timing) -> AnimationEnd {
        self.start(timing.driver(to))
    }

    /// Glides from `velocity` (per second; `None`: the current one),
    /// slowing down by `deceleration` per millisecond (0.998: a fling).
    pub fn decay(&self, velocity: Option<f32>, deceleration: f32) -> AnimationEnd {
        self.start(Driver::Decay {
            velocity,
            deceleration,
            clamp: None,
            bounce: 0.0,
            frame_rate: None,
        })
    }

    /// Like [`Self::decay`], within `min..=max`: it stops at a bound, or
    /// bounces back from it keeping `bounce` (0..1) of its speed.
    pub fn decay_within(
        &self,
        velocity: Option<f32>,
        deceleration: f32,
        (min, max): (f32, f32),
        bounce: f32,
    ) -> AnimationEnd {
        self.start(Driver::Decay {
            velocity,
            deceleration,
            clamp: Some((min, max)),
            bounce,
            frame_rate: None,
        })
    }

    /// Sets the offset added to the value (React Native's `setOffset`):
    /// bindings see value + offset, animations and `set` move the value.
    pub fn set_offset(&self, offset: f32) {
        self.0.act(|node| AnimationOp::SetOffset { node, offset });
    }

    /// Adds the offset to the value and clears it.
    pub fn flatten_offset(&self) {
        self.0.act(|node| AnimationOp::FlattenOffset { node });
    }

    /// Moves the value into the offset, leaving the value 0 (a drag then
    /// starts from where the last one left it).
    pub fn extract_offset(&self) {
        self.0.act(|node| AnimationOp::ExtractOffset { node });
    }

    /// See [`AnimatedNode::interpolate`].
    pub fn interpolate(&self, input: &[f32], output: &[f32]) -> AnimatedNode {
        self.0.interpolate(input, output)
    }

    /// See [`AnimatedNode::interpolate_colors`].
    pub fn interpolate_colors<C: Into<AdaptiveColor> + Copy>(
        &self,
        input: &[f32],
        colors: &[C],
    ) -> AnimatedNode {
        self.0.interpolate_colors(input, colors)
    }

    /// See [`AnimatedNode::interpolate_with`].
    pub fn interpolate_with(
        &self,
        input: &[f32],
        output: Output,
        interpolation: Interpolation,
    ) -> AnimatedNode {
        self.0.interpolate_with(input, output, interpolation)
    }

    /// See [`AnimatedNode::diff_clamp`].
    pub fn diff_clamp(
        &self,
        min: impl Into<AnimationOperand>,
        max: impl Into<AnimationOperand>,
    ) -> AnimatedNode {
        self.0.diff_clamp(min, max)
    }

    /// See [`AnimatedNode::diff_clamp_with`].
    pub fn diff_clamp_with(
        &self,
        min: impl Into<AnimationOperand>,
        max: impl Into<AnimationOperand>,
        options: DiffClamp,
    ) -> AnimatedNode {
        self.0.diff_clamp_with(min, max, options)
    }

    /// See [`AnimatedNode::add`].
    pub fn add(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.0.add(other)
    }

    /// See [`AnimatedNode::sub`].
    pub fn sub(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.0.sub(other)
    }

    /// See [`AnimatedNode::mul`].
    pub fn mul(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.0.mul(other)
    }

    /// See [`AnimatedNode::div`].
    pub fn div(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.0.div(other)
    }

    /// See [`AnimatedNode::modulo`].
    pub fn modulo(&self, other: impl Into<AnimationOperand>) -> AnimatedNode {
        self.0.modulo(other)
    }
}

impl Animated for AnimatedValue {
    fn animated_node(&self) -> AnimatedNode {
        self.0
    }
}

/// A composed animation (TS: `Animated.timing` / `spring` / `decay` /
/// `sequence` / `parallel` / `stagger` / `delay` / `loop`): a tree of
/// steps over animated values, run on the UI thread, each step starting at
/// the exact end of the one before (no round trip to the engine between
/// steps).
///
/// Build it once (in the view, captured by the listeners that run it) and
/// run it any number of times: [`Self::start`] runs it (stopping a run of
/// it going on) and returns its [`AnimationEnd`], [`Self::stop`] stops it
/// where it is, [`Self::reset`] stops it and puts its values back where
/// they were when it last started. Clones are the same animation; building a group from
/// animations makes a new one (its parts are copied in). It holds the nodes
/// of its values while it lives (values whose owner is gone are left
/// out), wherever it is kept.
///
/// ```ignore
/// let jump = Animation::sequence([
///     Animation::timing(&y, -36.0, Timing::new(220.0, Easing::EaseOut)),
///     Animation::spring(&y, 0.0, Spring::default()),
/// ]);
/// view().on_press(move || {
///     let end = jump.start();
/// })
/// ```
#[derive(Clone)]
pub struct Animation(Rc<Composed>);

struct Composed {
    spec: Composite,
    /// The nodes of the values it animates, held while it is.
    values: Vec<LiveNode>,
    run: Run,
}

/// An animation's identity in the graph.
struct Run {
    executor: Weak<Executor>,
    /// Its composite key (what resets restore by); 0 until it first runs.
    key: Cell<u32>,
    /// Its last run (0: none).
    animation: Cell<AnimationId>,
}

impl Drop for Run {
    fn drop(&mut self) {
        // A run going on goes on; the graph forgets the values to reset to.
        let key = self.key.get();
        if key != 0
            && let Some(executor) = self.executor.upgrade()
        {
            executor.act(Action::Animation(AnimationOp::ReleaseComposite { key }));
        }
    }
}

impl Animation {
    fn new(spec: Composite, values: Vec<LiveNode>) -> Self {
        let executor = values
            .first()
            .map(|n| n.0.executor.clone())
            .unwrap_or_default();
        Self(Rc::new(Composed {
            spec,
            values,
            run: Run {
                executor,
                key: Cell::new(0),
                animation: Cell::new(0),
            },
        }))
    }

    fn run(value: &AnimatedValue, driver: Driver) -> Self {
        let node = value.0.id();
        Self::new(
            Composite::Run { node, driver },
            value.0.live().into_iter().collect(),
        )
    }

    /// `value` moving to `to` as `timing` says.
    pub fn timing(value: &AnimatedValue, to: f32, timing: Timing) -> Self {
        Self::run(value, timing.driver(to))
    }

    /// `value` springing to `to`.
    pub fn spring(value: &AnimatedValue, to: f32, spring: Spring) -> Self {
        Self::run(value, spring.driver(to))
    }

    /// `value` gliding from `velocity` (per second; `None`: the current
    /// one), slowing down by `deceleration` per millisecond (0.998: a
    /// fling).
    pub fn decay(value: &AnimatedValue, velocity: Option<f32>, deceleration: f32) -> Self {
        Self::run(
            value,
            Driver::Decay {
                velocity,
                deceleration,
                clamp: None,
                bounce: 0.0,
                frame_rate: None,
            },
        )
    }

    /// Like [`Self::decay`], within `min..=max`: it stops at a bound, or
    /// bounces back from it keeping `bounce` (0..1) of its speed.
    pub fn decay_within(
        value: &AnimatedValue,
        velocity: Option<f32>,
        deceleration: f32,
        (min, max): (f32, f32),
        bounce: f32,
    ) -> Self {
        Self::run(
            value,
            Driver::Decay {
                velocity,
                deceleration,
                clamp: Some((min, max)),
                bounce,
                frame_rate: None,
            },
        )
    }

    /// `value` through `frames`, as CSS keyframes play (TS:
    /// `Animated.keyframes`): offsets spread as the Web Animations API
    /// spreads them, an easing per segment, iterations, a direction and a
    /// delay ([`KeyframeTiming`]).
    pub fn keyframes(
        value: &AnimatedValue,
        frames: impl IntoIterator<Item = Keyframe>,
        timing: KeyframeTiming,
    ) -> Self {
        let frames: Vec<Keyframe> = frames.into_iter().collect();
        Self::new(
            crate::animation::keyframes(value.0.id(), &frames, &timing),
            value.0.live().into_iter().collect(),
        )
    }

    /// A wait of `ms` milliseconds (in a sequence).
    pub fn delay(ms: f32) -> Self {
        Self::new(Composite::Delay(ms), Vec::new())
    }

    /// The spec and values of this animation.
    fn into_parts(self) -> (Composite, Vec<LiveNode>) {
        match Rc::try_unwrap(self.0) {
            Ok(Composed { spec, values, .. }) => (spec, values),
            Err(shared) => (shared.spec.clone(), shared.values.clone()),
        }
    }

    fn group(
        animations: impl IntoIterator<Item = Animation>,
        make: impl FnOnce(Vec<Composite>) -> Composite,
    ) -> Self {
        let mut specs = Vec::new();
        let mut values: Vec<LiveNode> = Vec::new();
        for animation in animations {
            let (spec, of) = animation.into_parts();
            specs.push(spec);
            for value in of {
                if !values.contains(&value) {
                    values.push(value);
                }
            }
        }
        Self::new(make(specs), values)
    }

    /// `animations` one after the other; it stops at the first that is
    /// stopped.
    pub fn sequence(animations: impl IntoIterator<Item = Animation>) -> Self {
        Self::group(animations, Composite::Sequence)
    }

    /// `animations` all at once; one stopped stops the others (see
    /// [`Self::stop_together`]).
    pub fn parallel(animations: impl IntoIterator<Item = Animation>) -> Self {
        Self::group(animations, |children| Composite::Parallel {
            children,
            stop_together: true,
        })
    }

    /// `animations` all at once, each starting `ms` milliseconds after the
    /// one before.
    pub fn stagger(ms: f32, animations: impl IntoIterator<Item = Animation>) -> Self {
        let staged = animations
            .into_iter()
            .enumerate()
            .map(|(i, a)| Self::sequence([Self::delay(ms * i as f32), a]));
        Self::parallel(staged)
    }

    /// `animations` all at once, each starting `ms` milliseconds after the
    /// one before, counted from `from` (TS: `Animated.stagger(ms, list, {
    /// from })`): from the center, a list ripples out from its middle.
    pub fn stagger_from(
        ms: f32,
        from: StaggerFrom,
        animations: impl IntoIterator<Item = Animation>,
    ) -> Self {
        let animations: Vec<Animation> = animations.into_iter().collect();
        let count = animations.len();
        let staged = animations.into_iter().enumerate().map(|(i, a)| {
            Self::sequence([
                Self::delay(ms * crate::animation::stagger_delay(i, count, from)),
                a,
            ])
        });
        Self::parallel(staged)
    }

    /// This animation over and over: `iterations` times, or until stopped
    /// with `None`; its values go back to where they were before each run
    /// (see [`Self::reset_before_iteration`]).
    pub fn looped(self, iterations: Option<u32>) -> Self {
        let (spec, values) = self.into_parts();
        Self::new(
            Composite::Loop {
                child: Box::new(spec),
                iterations,
                reset: true,
            },
            values,
        )
    }

    /// For a group made with [`Self::parallel`] or [`Self::stagger`]:
    /// whether one of its animations stopped stops the others (by
    /// default it does). Other animations stay as they are.
    pub fn stop_together(self, stop_together: bool) -> Self {
        let (mut spec, values) = self.into_parts();
        if let Composite::Parallel {
            stop_together: s, ..
        } = &mut spec
        {
            *s = stop_together;
        }
        Self::new(spec, values)
    }

    /// For a loop made with [`Self::looped`]: whether its values go back
    /// to where they were before each run (by default they do). Other
    /// animations stay as they are.
    pub fn reset_before_iteration(self, reset: bool) -> Self {
        let (mut spec, values) = self.into_parts();
        if let Composite::Loop { reset: r, .. } = &mut spec {
            *r = reset;
        }
        Self::new(spec, values)
    }

    /// Runs it, stopping a run of it going on (which ends `false`). It
    /// runs either way: await the end in a task to follow it up, or drop
    /// it. An animation of no values (only delays) has nothing to run on
    /// and ends at once.
    pub fn start(&self) -> AnimationEnd {
        let (end, slot) = Answer::new();
        let run = &self.0.run;
        let Some(executor) = run.executor.upgrade() else {
            if self.0.values.is_empty() {
                slot.borrow_mut().deliver(true);
            }
            return AnimationEnd(end);
        };
        self.stop();
        if run.key.get() == 0 {
            run.key.set(executor.next_animation_id());
        }
        let animation = executor.next_animation_id();
        run.animation.set(animation);
        executor.act(Action::Animate {
            op: AnimationOp::StartComposite {
                animation,
                key: run.key.get(),
                spec: self.0.spec.clone(),
            },
            animation,
            end: slot,
        });
        AnimationEnd(end)
    }

    /// Stops its run where it is (the run ends `false`).
    pub fn stop(&self) {
        let run = &self.0.run;
        let animation = run.animation.replace(0);
        if animation != 0
            && let Some(executor) = run.executor.upgrade()
        {
            executor.act(Action::Animation(AnimationOp::StopAnimation { animation }));
        }
    }

    /// Stops its run (which ends `false`) and puts its values back where
    /// they were when it last started.
    pub fn reset(&self) {
        let run = &self.0.run;
        run.animation.set(0);
        let key = run.key.get();
        if key != 0
            && let Some(executor) = run.executor.upgrade()
        {
            executor.act(Action::Animation(AnimationOp::ResetComposite { key }));
        }
    }
}

impl fmt::Debug for Animation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Animation").field(&self.0.spec).finish()
    }
}

/// Animated values for a view's opacity and the parts of its transform
/// (TS: `createMotion`), and motions to play on them: presets
/// ([`crate::animation::MotionPreset`]: entrances, exits, attention seekers,
/// loops) or keyframes of the app's own ([`MotionSpec`]). Bind it with
/// [`super::Styled::bind_motion`]. A `Copy` handle, kept by the owner
/// current when it is made, as an [`AnimatedValue`] is.
///
/// ```ignore
/// let card = motion().entering(MotionPreset::FadeInUp);
/// view().bind_motion(&card).on_press(move || {
///     card.play(MotionPreset::Pulse);
/// })
/// ```
#[derive(Clone, Copy)]
pub struct Motion {
    values: [AnimatedValue; 9],
}

impl fmt::Debug for Motion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Motion").finish_non_exhaustive()
    }
}

impl Motion {
    pub(crate) fn new(executor: &Rc<Executor>) -> Self {
        Self {
            values: MotionChannel::ALL.map(|c| AnimatedValue::new(executor, c.identity())),
        }
    }

    /// The value of `channel` (opacity 0..1, translations in points,
    /// rotations in degrees, scales).
    pub fn value(&self, channel: MotionChannel) -> AnimatedValue {
        self.values[channel.index()]
    }

    /// Starting where `motion` starts and playing it at once: a view that
    /// comes in shows its first frame where the motion begins.
    pub fn entering(self, motion: impl Into<MotionSpec>) -> Self {
        let motion = motion.into();
        for (channel, start) in motion.start_values() {
            self.value(channel).set(start);
        }
        let _ = self.play(motion);
        self
    }

    /// Plays `motion` on its channels (a new one interrupts the one
    /// playing). When the user asks for less motion
    /// ([`super::reduce_motion`]), it lands where it ends without moving.
    pub fn play(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
        self.run(motion.into(), super::reduce_motion())
    }

    /// Plays `motion` even when the user asks for less motion.
    pub fn play_ignoring_reduce_motion(&self, motion: impl Into<MotionSpec>) -> AnimationEnd {
        self.run(motion.into(), false)
    }

    /// `motion` as an [`Animation`] to compose, not started (TS:
    /// `motion.animation(..)`): `Animation::stagger_from(60.0,
    /// StaggerFrom::Center, cards.iter().map(|m| m.animation(..)))`. Like
    /// [`Self::play`], it lands at its end when the user asks for less
    /// motion (as things are when it is made).
    pub fn animation(&self, motion: impl Into<MotionSpec>) -> Animation {
        self.composed(motion.into(), super::reduce_motion())
    }

    fn composed(&self, motion: MotionSpec, reduced: bool) -> Animation {
        let nodes = self.values.map(|v| v.0.id());
        let held = self
            .values
            .iter()
            .filter_map(|v| v.0.live())
            .collect::<Vec<_>>();
        Animation::new(motion.composite(&nodes, reduced), held)
    }

    fn run(&self, motion: MotionSpec, reduced: bool) -> AnimationEnd {
        self.composed(motion, reduced).start()
    }

    /// Stops it where it is.
    pub fn stop(&self) {
        for value in &self.values {
            value.stop();
        }
    }

    /// Stops it and puts every channel back at rest.
    pub fn reset(&self) {
        for channel in MotionChannel::ALL {
            self.value(channel).set(channel.identity());
        }
    }
}

/// A timing a component's prop takes (TS `{ duration?: number; easing?:
/// Easing; delay?: number; frameRate?: number }`): the options of
/// `AnimatedValue.timing` in `nsh/animated`, with its defaults (300 ms,
/// ease in-out, no delay, the screen's highest rate).
impl super::JsValue for Timing {
    fn ts_type(_types: &mut super::TsTypes) -> String {
        "{ duration?: number; easing?: import(\"nsh\").Easing; delay?: number; frameRate?: number }"
            .into()
    }

    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
        let json = value.to_json()?;
        let Some(object) = json.as_object() else {
            return Err(value.expected("a timing: `{ duration, easing, delay }`"));
        };
        let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
        let default = Timing::default();
        Ok(Timing {
            duration_ms: num("duration").unwrap_or(default.duration_ms).max(0.0),
            easing: object
                .get("easing")
                .and_then(|e| crate::js::animation::easing(&JsonInput(Some(e))))
                .unwrap_or(default.easing),
            delay_ms: num("delay").unwrap_or(default.delay_ms).max(0.0),
            frame_rate: crate::style::frame_rate(num("frameRate")),
        })
    }

    fn to_js<'a>(
        &self,
        host: &'a dyn super::JsHost,
    ) -> Result<super::JsOwned<'a>, super::PropError> {
        let mut json = serde_json::json!({ "duration": self.duration_ms, "delay": self.delay_ms });
        if let Some(hz) = self.frame_rate {
            json["frameRate"] = hz.into();
        }
        Ok(super::JsOwned::new(host, host.json(&json)?))
    }
}

/// A spring a component's prop takes (TS `{ stiffness?: number; damping?:
/// number; mass?: number; velocity?: number; frameRate?: number }`): the
/// options of `AnimatedValue.spring` in `nsh/animated`, with its defaults.
impl super::JsValue for Spring {
    fn ts_type(_types: &mut super::TsTypes) -> String {
        "{ stiffness?: number; damping?: number; mass?: number; velocity?: number; frameRate?: number }"
            .into()
    }

    fn from_js(value: super::JsIn<'_>) -> Result<Self, super::PropError> {
        let json = value.to_json()?;
        let Some(object) = json.as_object() else {
            return Err(value.expected("a spring: `{ stiffness, damping, mass }`"));
        };
        let num = |key: &str| object.get(key).and_then(|v| v.as_f64()).map(|v| v as f32);
        let default = Spring::default();
        Ok(Spring {
            stiffness: num("stiffness").unwrap_or(default.stiffness),
            damping: num("damping").unwrap_or(default.damping),
            mass: num("mass").unwrap_or(default.mass),
            velocity: num("velocity"),
            frame_rate: crate::style::frame_rate(num("frameRate")),
        })
    }

    fn to_js<'a>(
        &self,
        host: &'a dyn super::JsHost,
    ) -> Result<super::JsOwned<'a>, super::PropError> {
        let mut json = serde_json::json!({
            "stiffness": self.stiffness,
            "damping": self.damping,
            "mass": self.mass,
        });
        if let Some(hz) = self.frame_rate {
            json["frameRate"] = hz.into();
        }
        Ok(super::JsOwned::new(host, host.json(&json)?))
    }
}

/// A JSON value as the core's decoders read JS values (an easing, an
/// image source).
pub(crate) struct JsonInput<'a>(pub(crate) Option<&'a crate::JsonValue>);

/// A JSON array, read by index.
pub(crate) struct JsonList<'a>(&'a [crate::JsonValue]);

impl<'a> crate::js::host::HostList for JsonList<'a> {
    type Item = JsonInput<'a>;

    fn len(&self) -> usize {
        self.0.len()
    }

    fn item(&self, index: usize) -> Option<JsonInput<'a>> {
        self.0.get(index).map(|v| JsonInput(Some(v)))
    }
}

impl<'a> crate::js::host::HostInput for JsonInput<'a> {
    type List = JsonList<'a>;

    fn is_nullish(&self) -> bool {
        self.0.is_none_or(|v| v.is_null())
    }

    fn is_object(&self) -> bool {
        self.0.is_some_and(|v| v.is_object() || v.is_array())
    }

    fn as_bool(&self) -> Option<bool> {
        self.0?.as_bool()
    }

    fn as_number(&self) -> Option<f64> {
        self.0?.as_f64()
    }

    fn as_string(&self) -> Option<String> {
        self.0?.as_str().map(str::to_owned)
    }

    fn field(&self, key: &str) -> Option<Self> {
        self.0?.get(key).map(|v| JsonInput(Some(v)))
    }

    fn as_list(&self) -> Option<JsonList<'a>> {
        self.0?.as_array().map(|a| JsonList(a))
    }

    fn entries(&self) -> Vec<(String, Self)> {
        match self.0.and_then(|v| v.as_object()) {
            Some(o) => o
                .iter()
                .map(|(k, v)| (k.clone(), JsonInput(Some(v))))
                .collect(),
            None => Vec::new(),
        }
    }

    fn truthy(&self) -> bool {
        match self.0 {
            None | Some(crate::JsonValue::Null) => false,
            Some(crate::JsonValue::Bool(b)) => *b,
            Some(crate::JsonValue::Number(n)) => n.as_f64().is_some_and(|n| n != 0.0),
            Some(crate::JsonValue::String(s)) => !s.is_empty(),
            Some(_) => true,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::element::reactive::{Runtime, create_root};

    fn released(executor: &Executor) -> usize {
        executor
            .take_actions()
            .into_iter()
            .filter(|a| matches!(a, Action::Animation(AnimationOp::Release { .. })))
            .count()
    }

    #[test]
    fn a_derived_chain_keeps_its_middle_nodes() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let (value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.5));
        // The chain's handles go with their owner; a binding of its end
        // holds the product too.
        let (chain_owner, end) = create_root(|| v.node().mul(2.0).sub(1.0));
        let bound = end.live().expect("live");
        chain_owner.dispose();
        assert_eq!(released(&executor), 0, "the product lives with the end");
        assert!(end.live().is_none(), "its handle is gone");
        drop(bound);
        assert_eq!(released(&executor), 2, "then both go");
        value_owner.dispose();
        assert_eq!(released(&executor), 1);
    }

    #[test]
    fn copies_are_the_same_value_in_every_closure() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let (_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
        let node = v.node().id();
        let _ = ops(&executor);
        // Two closures and the code after them use the one value.
        let press = move || v.set(1.0);
        let release = move || v.set_offset(2.0);
        press();
        release();
        let _ = v.timing(3.0, 100.0, Easing::Linear);
        assert!(matches!(
            &ops(&executor)[..],
            [
                AnimationOp::Set { node: a, value: 1.0 },
                AnimationOp::SetOffset { node: b, offset: 2.0 },
                AnimationOp::Start { node: c, .. },
            ] if [*a, *b, *c] == [node; 3]
        ));
        let copy = v;
        assert_eq!(copy, v);
        assert_eq!(
            format!("{v:?}"),
            format!("AnimatedValue(AnimatedNode({node}))")
        );
    }

    #[test]
    fn handles_do_nothing_once_their_owner_is_gone() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let (owner, (v, half)) = create_root(|| {
            let v = AnimatedValue::new(&executor, 0.0);
            (v, v.mul(0.5))
        });
        let jump = Animation::timing(&v, 1.0, Timing::default());
        let _ = ops(&executor);
        owner.dispose();
        // The value and its product go with their owner; the composite
        // holds the value's node while it lives.
        assert_eq!(ops(&executor), [AnimationOp::Release { node: half.id() }]);
        drop(jump);
        assert_eq!(
            ops(&executor),
            [AnimationOp::Release {
                node: v.node().id()
            }]
        );

        v.set(1.0);
        v.stop();
        v.set_offset(1.0);
        v.flatten_offset();
        v.extract_offset();
        let ended = v.spring(1.0, Spring::default());
        let tasks = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        assert!(!tasks.block_on(ended.into_future()), "unfinished, at once");
        drop(v.value());
        let derived = [
            v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
            v.add(&half),
            half.mul(2.0),
        ];
        assert!(derived.iter().all(|n| n.live().is_none()));
        drop(Animation::timing(&v, 1.0, Timing::default()).start());
        assert_eq!(ops(&executor), [], "nothing reaches the graph");
        // Handles keep their identity.
        let copy = half;
        assert_eq!(copy, half);
        assert_eq!(format!("{half:?}"), format!("AnimatedNode({})", half.id()));
    }

    #[test]
    fn deriving_again_finds_the_node_among_many() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let (_owner, (v, first, again, zeros)) = create_root(|| {
            let v = AnimatedValue::new(&executor, 0.0);
            let derive = || -> Vec<AnimatedNode> {
                (0..2_000)
                    .map(|i| v.interpolate(&[0.0, 1.0], &[0.0, i as f32]))
                    .collect()
            };
            let first = derive();
            let again = derive();
            // Zeros of either sign are one number: one node.
            let zeros = [
                v.interpolate(&[0.0, 1.0], &[0.0, 1.0]),
                v.interpolate(&[-0.0, 1.0], &[-0.0, 1.0]),
            ];
            (v, first, again, zeros)
        });
        assert!(first.iter().zip(&again).all(|(a, b)| a == b));
        let mut ids: Vec<_> = first.iter().map(AnimatedNode::id).collect();
        ids.dedup();
        assert_eq!(ids.len(), 2_000, "distinct keys, distinct nodes");
        assert_eq!(zeros[0], zeros[1]);
        assert_eq!(zeros[0], first[1]);
        let _ = v;
    }

    #[test]
    fn dead_derived_nodes_are_neither_found_nor_kept() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let (_value_owner, v) = create_root(|| AnimatedValue::new(&executor, 0.0));
        let (owner, gone) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
        let id = gone.id();
        owner.dispose();
        let (_owner, made) = create_root(|| v.interpolate(&[0.0, 1.0], &[2.0, 3.0]));
        assert_ne!(made.id(), id, "a dead node is made again");
        // Nodes made and dropped over and over are swept out as they go.
        for round in 0..50 {
            let (owner, _) = create_root(|| {
                (0..200)
                    .map(|i| v.interpolate(&[0.0, 1.0], &[round as f32, i as f32]))
                    .collect::<Vec<_>>()
            });
            owner.dispose();
        }
        let kept: usize = executor.derived().by_hash.values().map(Vec::len).sum();
        assert!(kept <= 2 * 200 + 64, "{kept} kept");
    }

    /// Deriving many distinct nodes, one by one, as a player's scene does:
    /// `cargo test --release -p nsh-core bench_derive -- --ignored
    /// --nocapture`.
    #[test]
    #[ignore = "benchmark"]
    fn bench_derive_many_nodes() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        for n in [5_000, 20_000] {
            let start = std::time::Instant::now();
            let (owner, _nodes) = create_root(|| {
                let v = AnimatedValue::new(&executor, 0.0);
                (0..n)
                    .map(|i| v.interpolate(&[0.0, 0.5, 1.0], &[0.0, i as f32, 1.0]))
                    .collect::<Vec<_>>()
            });
            println!("{n} derived nodes: {:?}", start.elapsed());
            owner.dispose();
            let _ = executor.take_actions();
        }
    }

    /// The graph operations `executor` was asked for (animations' ends
    /// dropped).
    fn ops(executor: &Executor) -> Vec<AnimationOp> {
        executor
            .take_actions()
            .into_iter()
            .filter_map(|a| match a {
                Action::Animation(op) | Action::Animate { op, .. } => Some(op),
                _ => None,
            })
            .collect()
    }

    fn timing(to: f32, ms: f32) -> Driver {
        Timing::new(ms, Easing::Linear).driver(to)
    }

    #[test]
    fn keyframes_staggers_and_motions_describe_their_trees() {
        use crate::animation::{MotionPreset, StaggerFrom};
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let values: Vec<AnimatedValue> =
            (0..3).map(|_| AnimatedValue::new(&executor, 0.0)).collect();
        let step = |v: &AnimatedValue| {
            Animation::keyframes(
                v,
                [Keyframe::new(0.0), Keyframe::new(1.0)],
                KeyframeTiming::new(100.0),
            )
        };
        let rippled = Animation::stagger_from(40.0, StaggerFrom::Center, values.iter().map(step));
        let Composite::Parallel { children, .. } = &rippled.0.spec else {
            panic!("{:?}", rippled.0.spec)
        };
        let delays: Vec<f32> = children
            .iter()
            .map(|c| match c {
                Composite::Sequence(s) => match s[0] {
                    Composite::Delay(ms) => ms,
                    _ => -1.0,
                },
                _ => -1.0,
            })
            .collect();
        assert_eq!(delays, [40.0, 0.0, 40.0]);

        let motion = Motion::new(&executor);
        executor.take_actions();
        let _ = motion.play_ignoring_reduce_motion(MotionPreset::Shake);
        let started = executor.take_actions().into_iter().find_map(|a| match a {
            Action::Animate {
                op: AnimationOp::StartComposite { spec, .. },
                ..
            } => Some(spec),
            _ => None,
        });
        let Some(Composite::Parallel { children, .. }) = started else {
            panic!("{started:?}")
        };
        // `shake` moves one channel: translateX.
        assert_eq!(children.len(), 1);
        let mut nodes = Vec::new();
        children[0].nodes(&mut nodes);
        assert_eq!(nodes, [motion.value(MotionChannel::TranslateX).node().id()]);
    }

    #[test]
    fn composites_describe_their_steps() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let (a, b) = (
            AnimatedValue::new(&executor, 0.0),
            AnimatedValue::new(&executor, 1.0),
        );
        let (na, nb) = (a.node().id(), b.node().id());
        let run = |node, to| Composite::Run {
            node,
            driver: timing(to, 100.0),
        };
        let step =
            |v: &AnimatedValue, to| Animation::timing(v, to, Timing::new(100.0, Easing::Linear));
        let staggered = Animation::stagger(50.0, [step(&a, 1.0), step(&b, 2.0)]);
        let delayed = |ms, c| Composite::Sequence(vec![Composite::Delay(ms), c]);
        assert_eq!(
            staggered.0.spec,
            Composite::Parallel {
                children: vec![delayed(0.0, run(na, 1.0)), delayed(50.0, run(nb, 2.0))],
                stop_together: true,
            }
        );
        let ids = |a: &Animation| a.0.values.iter().map(LiveNode::id).collect::<Vec<_>>();
        assert_eq!(ids(&staggered), [na, nb]);

        let looped = Animation::sequence([step(&a, 1.0), Animation::delay(10.0), step(&a, 0.0)])
            .looped(Some(3))
            .reset_before_iteration(false);
        assert_eq!(
            looped.0.spec,
            Composite::Loop {
                child: Box::new(Composite::Sequence(vec![
                    run(na, 1.0),
                    Composite::Delay(10.0),
                    run(na, 0.0)
                ])),
                iterations: Some(3),
                reset: false,
            }
        );
        // Each value once.
        assert_eq!(ids(&looped), [na]);
        let apart = Animation::parallel([step(&a, 1.0)]).stop_together(false);
        assert!(matches!(
            apart.0.spec,
            Composite::Parallel {
                stop_together: false,
                ..
            }
        ));
        // A delay on its own driver.
        let delayed = Animation::timing(
            &a,
            1.0,
            Timing {
                delay_ms: 40.0,
                ..Timing::default()
            },
        );
        assert!(matches!(
            delayed.0.spec,
            Composite::Run {
                driver: Driver::Timing {
                    delay_ms: 40.0,
                    duration_ms: 300.0,
                    easing: Easing::EaseInOut,
                    ..
                },
                ..
            }
        ));
    }

    #[test]
    fn composites_start_stop_reset_and_release_by_key() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let x = AnimatedValue::new(&executor, 0.0);
        let _ = ops(&executor);
        let jump = Animation::sequence([
            Animation::timing(&x, 10.0, Timing::default()),
            Animation::spring(&x, 0.0, Spring::default()),
        ]);
        // Nothing until it runs.
        jump.stop();
        jump.reset();
        assert_eq!(ops(&executor), []);

        let _ = jump.start();
        let [
            AnimationOp::StartComposite {
                animation,
                key,
                spec,
            },
        ] = &ops(&executor)[..]
        else {
            panic!("a composite start");
        };
        assert_eq!((animation % 2, key % 2), (1, 1), "the core's ids are odd");
        assert_eq!(spec, &jump.0.spec);
        let (first, key) = (*animation, *key);

        // Again: the run going on stops first; the key stays.
        let _ = jump.clone().start();
        let again = ops(&executor);
        assert!(matches!(
            &again[..],
            [
                AnimationOp::StopAnimation { animation: a },
                AnimationOp::StartComposite { animation: b, key: k, .. },
            ] if *a == first && *b != first && *k == key
        ));
        jump.stop();
        assert!(matches!(
            &ops(&executor)[..],
            [AnimationOp::StopAnimation { .. }]
        ));
        jump.stop();
        assert_eq!(ops(&executor), [], "stopped once");
        jump.reset();
        assert_eq!(ops(&executor), [AnimationOp::ResetComposite { key }]);

        drop(jump);
        assert_eq!(ops(&executor), [AnimationOp::ReleaseComposite { key }]);
    }

    #[test]
    fn delays_alone_end_at_once() {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .build()
            .unwrap();
        let end = Animation::sequence([Animation::delay(100.0)]).start();
        assert!(runtime.block_on(end.into_future()));
    }

    #[test]
    fn values_derive_like_their_nodes() {
        let runtime = Runtime::default();
        let _entered = runtime.enter();
        let executor = Rc::new(Executor::default());
        let t = AnimatedValue::new(&executor, 0.0);
        let right = Interpolation {
            extrapolate_right: Extrapolate::Extend,
            ..Interpolation::default()
        };
        let angle = t.interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right);
        let [
            ..,
            AnimationOp::CreateInterpolate {
                extrapolate_left,
                extrapolate_right,
                easing,
                ..
            },
        ] = &ops(&executor)[..]
        else {
            panic!("an interpolation");
        };
        assert_eq!(
            (*extrapolate_left, *extrapolate_right, *easing),
            (Extrapolate::Clamp, Extrapolate::Extend, Easing::Linear)
        );
        // The same node as through `node()`.
        assert_eq!(
            angle,
            t.node()
                .interpolate_with(&[0.0, 1.0], Output::Numbers(vec![0.0, 180.0]), right)
        );
        assert_eq!(t.diff_clamp(0.0, 44.0), t.node().diff_clamp(0.0, 44.0));
        assert_eq!(t.mul(-1.0), t.node().mul(-1.0));
    }

    #[test]
    fn curves_sample_as_the_graph_runs_them() {
        // A spring from 0 to 1, one value a frame at 60 Hz, at rest at its
        // end; at 120 Hz about twice the frames.
        let spring = sample_spring(0.0, 1.0, Spring::default(), 60.0);
        assert_eq!(spring[0], 0.0);
        assert!((spring.last().unwrap() - 1.0).abs() < 1e-3, "{spring:?}");
        let fast = sample_spring(0.0, 1.0, Spring::default(), 120.0);
        assert!(fast.len() > spring.len() * 3 / 2, "{}", fast.len());
        // A spring that never rests stops at the cap.
        let undamped = Spring {
            damping: 0.0,
            ..Spring::default()
        };
        assert_eq!(
            sample_spring(0.0, 1.0, undamped, 60.0).len(),
            crate::animation::MAX_SAMPLES
        );
        // A fling glides on and slows down; within bounds it stops at one.
        let decay = sample_decay(0.0, 1000.0, 0.998, 60.0);
        assert!(decay.windows(2).all(|w| w[1] >= w[0]), "{decay:?}");
        assert!(*decay.last().unwrap() > 400.0, "{decay:?}");
        let within = sample_decay_within(0.0, 1000.0, 0.998, (0.0, 100.0), 0.0, 60.0);
        assert!(within.iter().all(|&x| (0.0..=100.0).contains(&x)));
        assert_eq!(*within.last().unwrap(), 100.0);
        // An easing's curve: both ends.
        let curve = super::super::sample_easing(Easing::EaseInOut, 5);
        assert_eq!((curve[0], curve[4], curve.len()), (0.0, 1.0, 5));
    }
}