bevy-react 0.3.0

Drive bevy_ui from a React app over an embedded V8 runtime.
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
//! CSS-like `transition`: declarative easing of `transform` / `opacity` /
//! `backgroundColor` between style states.
//!
//! The clunky way to "scale a button down on press" is to allocate a shared
//! value and hand-wire `onPointerDown`/`onPointerUp` to drivers. A `transition`
//! instead lets a plain style change — a re-render, or a `hoverStyle`/`pressStyle`
//! kicking in — *ease* to its new value. It reuses the animations crate's driver
//! runtime ([`Runner`]) rather than a parallel engine.
//!
//! ## How it fits the style pipeline
//!
//! Every style change funnels through [`crate::ui_map::apply_style`] — both the
//! base re-render path (`Op::Update`) and the hover/press path
//! ([`crate::reconcile::apply_interaction_styles`], which re-applies the *merged*
//! style for the current `Interaction`). So `apply_style` is the one place that
//! always knows the resolved target. It stamps a [`TransitionInput`] (the spec +
//! the resolved per-channel target) — a *stateless input* the engine reads but
//! never writes, so there's no feedback loop with the live `UiTransform`/color it
//! animates.
//!
//! [`drive_transitions`] then runs after `apply_interaction_styles`: it advances a
//! per-entity [`TransitionState`] (one [`Runner`] per channel) toward the input's
//! target and writes the interpolated value onto `UiTransform`/`BackgroundColor`/
//! alpha — *last* in the frame, so a coincident re-render's snap value never wins.
//!
//! A channel also driven by an inline `{ animated }` binding is left to the animations
//! plugin: the transition skips any channel bound by the entity's `AnimatedNode`.

use crate::animations::{
    AnimatableProperty, AnimatedNode, Driver, Easing, Lerp, Runner, build_runner,
    build_ui_transform,
};
use bevy::ecs::query::QueryData;
use bevy::prelude::*;
use bevy::ui::{ScrollPosition, UiTransform};
use serde::Deserialize;

use crate::protocol::{AnimatableField, Length, Style, Time as WireTime};
use crate::ui_map::{length_to_val, parse_color};

mod transform3d;

/// CSS-like per-channel transition timing, set on [`Style::transition`]. Each
/// field, if present, makes that channel ease on change; `all` is the fallback for
/// channels without an explicit entry. `transform` covers all six transform
/// channels together.
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Transition {
    /// Fallback applied to any channel without its own entry.
    pub all: Option<ChannelTransition>,
    /// Applies to every transform channel (translate/scale/rotate).
    pub transform: Option<ChannelTransition>,
    pub opacity: Option<ChannelTransition>,
    pub background_color: Option<ChannelTransition>,
    /// Applies to every size channel (width/height/maxWidth/maxHeight). These are
    /// *layout* properties — easing one re-flows the surrounding content (a real
    /// accordion), unlike the post-layout `transform`.
    pub size: Option<ChannelTransition>,
    /// Eases the scroll offset (`ScrollPosition`) of an `overflow: scroll` node
    /// toward its target on change — the target being a controlled `scrollTop`/
    /// `scrollLeft`, a `scrollTo`-style jump, or accumulated wheel input. Covers
    /// both axes. Unlike the others, scroll's target lives in `Props` (it's a
    /// controlled value), so it's fed by the scroll write path, not `from_style`.
    pub scroll: Option<ChannelTransition>,
    /// Eases the layer-based `filter` chain (see [`crate::filters`]) between
    /// style states, whole-value: matching chains interpolate their packed
    /// params; a chain that grows/shrinks at the end over built-in filters
    /// fades through identity values (hover-adds-blur fades in); anything
    /// else swaps at the midpoint. Unlike the others, the *target* doesn't
    /// ride [`TransitionInput`] — it is read live from
    /// [`crate::filters::FilterInput`] (a filter-only delta re-stamps that
    /// component but not the input).
    pub filter: Option<ChannelTransition>,
    /// Eases the `backdropFilter` chain — the second, independent instance of
    /// the `filter` channel (same whole-value strategy, same target rule: the
    /// target is read live from [`crate::filters::BackdropInput`], not
    /// [`TransitionInput`]). The same ease-to-empty snap applies: unsetting
    /// `backdropFilter` demotes the layer (no resolved chain to write into),
    /// so keep an identity entry — e.g. `{ name: "blur", params: { radius:
    /// 0 } }` — in the base chain when removal should ease.
    pub backdrop_filter: Option<ChannelTransition>,
    /// Applies to every `transform3d` channel together (field-wise easing of
    /// the composite-time 3D transform on a promoted layer — see
    /// [`crate::layer::transform3d`]). `perspective` snaps whenever either
    /// endpoint is orthographic (no numeric identity for "no perspective");
    /// unsetting the whole `transform3d` style demotes the layer and snaps,
    /// like `filter`'s ease-to-empty — keep an identity `{}` in the base
    /// style when removal should ease.
    pub transform3d: Option<ChannelTransition>,
}

impl Transition {
    /// The transition for the transform channels (explicit, else `all`).
    pub fn for_transform(&self) -> Option<&ChannelTransition> {
        self.transform.as_ref().or(self.all.as_ref())
    }
    /// The transition for opacity (explicit, else `all`).
    pub fn for_opacity(&self) -> Option<&ChannelTransition> {
        self.opacity.as_ref().or(self.all.as_ref())
    }
    /// The transition for background color (explicit, else `all`).
    pub fn for_background(&self) -> Option<&ChannelTransition> {
        self.background_color.as_ref().or(self.all.as_ref())
    }
    /// The transition for the size channels (explicit, else `all`).
    pub fn for_size(&self) -> Option<&ChannelTransition> {
        self.size.as_ref().or(self.all.as_ref())
    }
    /// The transition for the scroll offset (explicit, else `all`).
    pub fn for_scroll(&self) -> Option<&ChannelTransition> {
        self.scroll.as_ref().or(self.all.as_ref())
    }
    /// The transition for the filter chain (explicit, else `all`).
    pub fn for_filter(&self) -> Option<&ChannelTransition> {
        self.filter.as_ref().or(self.all.as_ref())
    }
    /// The transition for the backdrop-filter chain (explicit, else `all`).
    pub fn for_backdrop_filter(&self) -> Option<&ChannelTransition> {
        self.backdrop_filter.as_ref().or(self.all.as_ref())
    }
    /// The transition for the transform3d channels (explicit, else `all`).
    pub fn for_transform3d(&self) -> Option<&ChannelTransition> {
        self.transform3d.as_ref().or(self.all.as_ref())
    }
}

/// Timing for one channel. A spring (any of `stiffness`/`damping` set) or, by
/// default, a timing curve. `duration`/`delay` are [`WireTime`]s: a bare number is
/// milliseconds (the JS-facing unit), a string carries an explicit unit
/// (`"200ms"`/`"0.2s"`), and both decode to the seconds the [`Driver`] consumes.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChannelTransition {
    /// Timing duration (default `0.3s`). Ignored for a spring.
    pub duration: Option<WireTime>,
    #[serde(default)]
    pub easing: Easing,
    /// Hold this long before easing (default `0`).
    #[serde(default)]
    pub delay: WireTime,
    /// Spring stiffness; presence (with/without `damping`) selects a spring.
    pub stiffness: Option<f32>,
    pub damping: Option<f32>,
    #[serde(default = "default_mass")]
    pub mass: f32,
}

fn default_mass() -> f32 {
    1.0
}

impl ChannelTransition {
    /// Build the [`Driver`] that eases the value to `to` from its live reading.
    /// A spring if `stiffness`/`damping` are present, else a (optionally delayed)
    /// timing curve.
    fn to_driver(&self, to: f32) -> Driver {
        if self.stiffness.is_some() || self.damping.is_some() {
            Driver::Spring {
                to,
                stiffness: self.stiffness.unwrap_or(100.0),
                damping: self.damping.unwrap_or(10.0),
                mass: self.mass,
            }
        } else {
            let timing = Driver::Timing {
                to,
                duration: self.duration.map(WireTime::seconds).unwrap_or(0.3),
                easing: self.easing,
            };
            let delay = self.delay.seconds();
            if delay > 0.0 {
                Driver::Delay {
                    delay,
                    animation: Box::new(timing),
                }
            } else {
                timing
            }
        }
    }
}

/// The resolved per-channel target for a transitioning entity, plus the spec.
/// Written by [`crate::ui_map::apply_style`] from the *merged* style and read each
/// frame by [`drive_transitions`]. Never written by the engine — keeping it free
/// of the live components it animates avoids a target-chases-animation feedback
/// loop. `None` on a channel means "unspecified" (its identity default is used).
#[derive(Component, Debug, Clone, Default)]
pub struct TransitionInput {
    pub spec: Transition,
    pub translate_x: Option<Length>,
    pub translate_y: Option<Length>,
    pub scale: Option<f32>,
    pub scale_x: Option<f32>,
    pub scale_y: Option<f32>,
    pub rotate: Option<f32>,
    pub opacity: Option<f32>,
    /// Target background color as straight rgba (no opacity folded in — the
    /// opacity channel owns alpha, applied after the color, like the animated path).
    pub background_color: Option<[f32; 4]>,
    // Size targets, written onto `Node` (layout). `None` → unset (`Val::Auto`).
    pub width: Option<Length>,
    pub height: Option<Length>,
    pub max_width: Option<Length>,
    pub max_height: Option<Length>,
    /// Target `transform3d` params, eased field-wise onto the layer's
    /// [`LayerTransform3d`](crate::layer::transform3d::LayerTransform3d).
    pub transform3d: Option<crate::protocol::Transform3d>,
}

impl TransitionInput {
    /// Build the input from a resolved style, or `None` if it has no `transition`.
    fn from_style(style: &Style) -> Option<Self> {
        let spec = style.transition.clone()?;
        let t = style.transform.clone().unwrap_or_default();
        // `static_val` throughout: an `{ animated }` channel has no static
        // target to ease toward — it reads as unset here, and the per-channel
        // skip rules park it anyway (bindings win over transitions).
        Some(Self {
            spec,
            translate_x: t.translate_x.static_val(),
            translate_y: t.translate_y.static_val(),
            scale: t.scale.static_val(),
            scale_x: t.scale_x.static_val(),
            scale_y: t.scale_y.static_val(),
            rotate: t.rotate.static_val().map(crate::protocol::Angle::radians),
            opacity: style.opacity.static_val(),
            background_color: style
                .background_color
                .static_ref()
                .map(|hex| color_to_rgba(parse_color(hex))),
            width: style.width.static_val(),
            height: style.height.static_val(),
            max_width: style.max_width.static_val(),
            max_height: style.max_height.static_val(),
            transform3d: style.transform3d.clone(),
        })
    }
}

/// Per-entity transition runtime: one [`Runner`]-backed channel per animatable
/// property. Persists across re-renders (the engine owns it); created lazily by
/// [`apply_transition`]. `#[require(UiTransform)]` so the drive query always
/// matches even for an opacity/color-only transition.
#[derive(Component, Default)]
#[require(UiTransform)]
pub struct TransitionState {
    translate_x: ProgressChannel<Length>,
    translate_y: ProgressChannel<Length>,
    scale: Channel,
    scale_x: Channel,
    scale_y: Channel,
    rotate: Channel,
    opacity: Channel,
    color: ProgressChannel<[f32; 4]>,
    width: ProgressChannel<Length>,
    height: ProgressChannel<Length>,
    max_width: ProgressChannel<Length>,
    max_height: ProgressChannel<Length>,
    filter: FilterChannel,
    backdrop_filter: FilterChannel,
    transform3d: transform3d::Transform3dChannels,
    initialized: bool,
}

/// The whole-value `filter` channel: eases a promoted root's
/// [`crate::filters::ResolvedFilterChain`] packed params between wire targets
/// (see [`crate::filters::plan_filter_ease`] for the strategy). Unlike the
/// scalar channels, its current reading cannot be re-read from the component —
/// [`crate::filters::resolve_chains`] snaps the component to the new
/// target on the retarget frame, before this system runs — so the state owns
/// the last-written pass list (the `ProgressChannel` state-owned-current
/// pattern, list-shaped).
#[derive(Default)]
struct FilterChannel {
    /// The last wire chain seen (retarget detection). Empty = no filter.
    wire: crate::filters::FilterChain,
    /// The pass list this channel last wrote (or adopted from the resolver) —
    /// the next ease's start.
    current: Vec<crate::filters::ResolvedFilterPass>,
    /// The in-flight ease, present only while animating. A single `Option`
    /// so the runner and its plan can never go out of sync.
    ease: Option<ActiveFilterEase>,
}

/// An armed filter ease: the [`Runner`] eases progress 0→1 and the plan turns
/// that progress into a pass list. Armed together at retarget, dropped
/// together on settle/teardown.
struct ActiveFilterEase {
    runner: Runner,
    ease: crate::filters::FilterEase,
}

impl FilterChannel {
    /// Advance the filter chain toward the wire target in `input`, writing the
    /// eased packed params into `resolved`. Returns `true` when it wrote —
    /// the caller pushes composite-only dirt (filter output never dirties the
    /// capture, which holds unfiltered content).
    ///
    /// Three writers touch [`crate::filters::ResolvedFilterChain`]; precedence
    /// runs resolver → transition → bindings. On the retarget frame
    /// [`crate::filters::resolve_chains`] (ordered before
    /// [`drive_transitions`]) *snaps* the component to the new target; this
    /// method *eases* over that snap — starting from the state-owned
    /// `current`, the last value this channel wrote, never the
    /// already-snapped component; and per-param animation bindings
    /// (`filter[<i>].<param>`) *re-assert* individual params on top, winning
    /// by gating this channel out via `skip_filter` (the imperative-wins
    /// pattern of the scalar channels, coarse: any filter binding parks the
    /// whole channel).
    ///
    /// The target rides the wire-chain component (`FilterInput` /
    /// `BackdropInput` — the caller projects to the inner [`FilterChain`]),
    /// NOT [`TransitionInput`] — a chain-only delta dirties the
    /// FILTER/BACKDROP|LAYER groups, never TRANSITION, so a target stamped
    /// into the input would go stale; the chain component is re-stamped by
    /// that same delta. Both channel instances (filter, backdropFilter) run
    /// this same code over their own component pair.
    fn drive(
        &mut self,
        input: Option<&crate::filters::FilterChain>,
        mut resolved: Option<Mut<crate::filters::ResolvedFilterChain>>,
        spec: Option<&ChannelTransition>,
        registry: Option<&crate::filters::FilterRegistry>,
        assets: Option<&AssetServer>,
        dt: f32,
    ) -> bool {
        let retargeted = match input {
            Some(fi) => *fi != self.wire,
            None => !self.wire.0.is_empty(),
        };
        if retargeted {
            let to_wire = input.cloned().unwrap_or_default();
            let from_wire = std::mem::replace(&mut self.wire, to_wire);
            match (spec, resolved.as_deref()) {
                // Ease only toward a live resolved chain. An emptied or
                // unresolvable target has no component to write into
                // (unset `filter` demotes the layer; an all-invalid chain
                // attaches none), so it snaps below.
                (Some(spec), Some(chain)) if !self.wire.0.is_empty() => {
                    self.ease = Some(ActiveFilterEase {
                        runner: build_runner(&spec.to_driver(1.0), 0.0),
                        ease: crate::filters::plan_filter_ease(
                            &from_wire,
                            &self.wire,
                            self.current.clone(),
                            chain.passes.clone(),
                            registry,
                            assets,
                            chain.scale,
                        ),
                    });
                }
                _ => {
                    // Snap: adopt whatever the resolver produced.
                    self.current = resolved
                        .as_deref()
                        .map(|c| c.passes.clone())
                        .unwrap_or_default();
                    self.ease = None;
                }
            }
        }
        let mut wrote = false;
        if let Some(mut active) = self.ease.take() {
            match resolved.as_mut() {
                Some(resolved) => {
                    let (p, done) = active.runner.step(dt);
                    // Completion writes the resolver's own snapped output,
                    // bit-exact, so the two writers agree and stop
                    // churning (the stage-interplay rule: bake the final
                    // value, don't approximate it).
                    let new = if done {
                        active.ease.settle().to_vec()
                    } else {
                        active.ease.sample(p)
                    };
                    // Compare via `Deref` first so a no-op frame doesn't
                    // trip change detection.
                    if resolved.passes != new {
                        let chain = &mut **resolved;
                        chain.passes = new.clone();
                        chain.version = chain.version.wrapping_add(1);
                        wrote = true;
                    }
                    self.current = new;
                    if !done {
                        self.ease = Some(active);
                    }
                }
                None => {
                    // The chain vanished mid-ease (demotion tore the
                    // layer down): drop the ease and forget the passes.
                    self.current = Vec::new();
                }
            }
        }
        wrote
    }
}

/// One scalar channel: its current reading, last target, and active driver.
#[derive(Default)]
struct Channel {
    current: f32,
    target: f32,
    runner: Option<Runner>,
}

impl Channel {
    /// Snap to `value` without animating (used to seed the resting state so an
    /// element doesn't animate from zero when it first appears).
    fn init(&mut self, value: f32) {
        self.current = value;
        self.target = value;
        self.runner = None;
    }

    /// Advance toward `target`. `spec` `Some` eases; `None` snaps. Returns the
    /// current value.
    fn drive(&mut self, target: f32, spec: Option<&ChannelTransition>, dt: f32) -> f32 {
        if target != self.target {
            self.target = target;
            match spec {
                Some(s) => self.runner = Some(build_runner(&s.to_driver(target), self.current)),
                None => {
                    self.current = target;
                    self.runner = None;
                }
            }
        }
        if let Some(r) = self.runner.as_mut() {
            let (v, done) = r.step(dt);
            self.current = v;
            if done {
                self.runner = None;
            }
        }
        self.current
    }
}

/// A progress-lerped channel (colors, [`Length`]s): a single [`Runner`] eases a
/// progress value 0→1 and the reading lerps from `start` to `target`. Used for
/// quantities that can't be time-stepped directly in value space (a color's four
/// channels move together; a `Length` carries a unit). [`ProgressChannel::drive`]
/// returns the current reading every frame — a caller writing a relayout-
/// triggering target (`Node`) compares before writing, like every other apply
/// path.
#[derive(Default)]
struct ProgressChannel<T> {
    current: T,
    target: T,
    start: T,
    runner: Option<Runner>,
}

impl<T: Lerp + PartialEq> ProgressChannel<T> {
    /// Snap to `value` without animating (used to seed the resting state so an
    /// element doesn't animate from zero when it first appears).
    fn init(&mut self, value: T) {
        self.current = value;
        self.target = value;
        self.runner = None;
    }

    /// Advance toward `target`. `spec` `Some` eases; `None` snaps. Returns the
    /// current reading.
    fn drive(&mut self, target: T, spec: Option<&ChannelTransition>, dt: f32) -> T {
        if target != self.target {
            self.target = target;
            match spec {
                Some(s) => {
                    self.start = self.current;
                    self.runner = Some(build_runner(&s.to_driver(1.0), 0.0));
                }
                None => {
                    self.current = target;
                    self.runner = None;
                }
            }
        }
        if let Some(r) = self.runner.as_mut() {
            let (p, done) = r.step(dt);
            self.current = self.start.lerp(self.target, p);
            if done {
                self.current = self.target;
                self.runner = None;
            }
        }
        self.current
    }
}

/// Interpolate two lengths of the same unit; mixed units or `auto` can't be
/// interpolated, so it snaps to the target.
impl Lerp for Length {
    fn lerp(self, other: Self, t: f32) -> Self {
        use Length::*;
        let lerp = |x: f32, y: f32| x + (y - x) * t;
        match (self, other) {
            (Px(x), Px(y)) => Px(lerp(x, y)),
            (Percent(x), Percent(y)) => Percent(lerp(x, y)),
            (Vw(x), Vw(y)) => Vw(lerp(x, y)),
            (Vh(x), Vh(y)) => Vh(lerp(x, y)),
            (VMin(x), VMin(y)) => VMin(lerp(x, y)),
            (VMax(x), VMax(y)) => VMax(lerp(x, y)),
            _ => other,
        }
    }
}

/// The scroll-easing **spec** input: the `transition.scroll` timing, reinserted
/// fresh on every render (like [`TransitionInput`]) so a changed spec takes effect.
/// Present only while `transition.scroll` (or `all`) is set. The *target* it eases
/// toward is NOT here — scroll's target is a controlled `Props` value, fed into
/// [`ScrollTransitionState`] by the scroll write path / wheel handler.
#[derive(Component, Debug, Clone)]
pub struct ScrollTransitionInput(pub ChannelTransition);

/// The scroll-easing **runtime state**: the target offset plus a per-axis eased
/// [`Channel`]. Persists across re-renders ([`insert_if_new`]). `target` is written
/// by the feeders ([`crate::reconcile::update_controlled_scroll`] and
/// `crate::scroll::apply_scroll`); [`drive_scroll_transition`] eases `ScrollPosition`
/// toward it. Mirrors the [`TransitionState`] half of the split.
#[derive(Component, Default)]
pub struct ScrollTransitionState {
    /// The offset to ease toward (already clamped to the scroll range by the feeder).
    pub(crate) target: Vec2,
    x: Channel,
    y: Channel,
    initialized: bool,
}

impl ScrollTransitionState {
    /// Snap the eased state to `value`: target + both channels, runners dropped.
    /// Used when the offset is manipulated directly (scrollbar thumb drag /
    /// track click) so easing neither lags nor reverts the direct write.
    pub(crate) fn snap_to(&mut self, value: Vec2) {
        self.target = value;
        self.x.init(value.x);
        self.y.init(value.y);
        self.initialized = true;
    }
}

/// Stamp (or clear) the scroll-ease components from `transition.scroll`. Called
/// from the reconciler's generic node paths (scroll containers are plain `<node>`s),
/// alongside `apply_scroll_listener`/`apply_scroll_step`. The spec input is always
/// reinserted (so a spec change lands); the state is created once and persists.
pub fn apply_scroll_transition(ec: &mut EntityCommands, style: &Option<Style>) {
    match style
        .as_ref()
        .and_then(|s| s.transition.as_ref())
        .and_then(|t| t.for_scroll())
    {
        Some(spec) => {
            ec.insert(ScrollTransitionInput(spec.clone()));
            ec.insert_if_new(ScrollTransitionState::default());
        }
        None => {
            ec.remove::<ScrollTransitionInput>();
            ec.remove::<ScrollTransitionState>();
        }
    }
}

/// Ease each `ScrollTransitionState` node's `ScrollPosition` toward its `target`
/// using the same per-channel [`Runner`] as [`drive_transitions`]. Writes only on a
/// frame the eased value actually moved, so a settled offset doesn't spam
/// `Changed<ScrollPosition>` (and thus `onScroll`). The target is pre-clamped by the
/// feeders; Bevy clamps the *rendered* offset regardless.
///
/// A `ScrollPosition` that moved *underneath* the easing (it no longer matches the
/// channels' last-written value) was written directly by scrollbar manipulation —
/// Bevy's widget writes the offset itself on thumb drag and track-click paging —
/// and snaps: direct manipulation bypasses the animation entirely.
pub fn drive_scroll_transition(
    time: Res<Time>,
    mut query: Query<(
        &ScrollTransitionInput,
        &mut ScrollTransitionState,
        &mut ScrollPosition,
    )>,
) {
    let dt = time.delta_secs();
    for (input, mut state, mut pos) in &mut query {
        // Seed resting state to the live offset so the first target change eases from
        // where the node actually is, not from zero.
        if !state.initialized {
            state.x.init(pos.0.x);
            state.y.init(pos.0.y);
            state.target = pos.0;
            state.initialized = true;
        }
        // After a drive the offset exactly equals (x.current, y.current) — on eased
        // containers every in-crate feeder writes `state.target`, so a mismatch means
        // the scrollbar widget wrote `ScrollPosition` directly this frame (thumb
        // drag, track-click page, or the final release-frame write): snap to it.
        let current = Vec2::new(state.x.current, state.y.current);
        if pos.0 != current {
            state.snap_to(pos.0);
            continue;
        }
        let spec = &input.0;
        let target = state.target;
        let nx = state.x.drive(target.x, Some(spec), dt);
        let ny = state.y.drive(target.y, Some(spec), dt);
        // Conditional write: equal assignment would still trip change detection.
        if pos.0.x != nx || pos.0.y != ny {
            pos.0 = Vec2::new(nx, ny);
        }
    }
}

/// Stamp (or clear) the transition components on a host element. Called from
/// [`crate::ui_map::apply_style`] with the resolved style, so the input always
/// reflects the current `Interaction` (base / hover / press). Sibling to
/// `apply_animated` in the reconciler's apply pattern.
pub fn apply_transition(ec: &mut EntityCommands, style: &Option<Style>) {
    match style.as_ref().and_then(TransitionInput::from_style) {
        Some(input) => {
            ec.insert(input);
            // The runtime state persists across re-renders, so only create it once.
            ec.insert_if_new(TransitionState::default());
        }
        None => {
            ec.remove::<TransitionInput>();
            ec.remove::<TransitionState>();
        }
    }
}

/// The components a transition can drive, plus the read-only inputs that gate how
/// it drives them. A `QueryData` struct (rather than a tuple) so a new transition
/// target component is one field, not a tuple-arity problem — the filter
/// channel's fields (`filter_input`/`resolved_filter`) live here already.
/// The per-param filter bindings (`filter[<i>].<param>`) write through the
/// *animation side* instead: `AnimTargets` (the animations applier's mirror
/// of this struct) carries its own resolved-chain field. Every target is
/// optional except `UiTransform` (required by [`TransitionState`]).
#[derive(QueryData)]
#[query_data(mutable)]
pub struct TransitionTargets {
    transform: &'static mut UiTransform,
    bg: Option<&'static mut BackgroundColor>,
    text: Option<&'static mut TextColor>,
    image: Option<&'static mut ImageNode>,
    node: Option<&'static mut Node>,
    /// The node's derived animation bindings; any channel they drive is skipped.
    anim: Option<&'static AnimatedNode>,
    // On a promoted layer root (see `crate::layer`) a transitioned `opacity`
    // drives the composite-time group alpha instead of the color folds.
    promoted: Option<&'static crate::layer::PromotedLayer>,
    layer_alpha: Option<&'static mut crate::layer::LayerGroupAlpha>,
    /// The wire `filter` chain — the filter channel's *target*. Read here
    /// (not from [`TransitionInput`]) because a filter-only delta re-stamps
    /// this component but never the input: the `filter` style field is in the
    /// FILTER|LAYER dirty groups, not TRANSITION.
    filter_input: Option<&'static crate::filters::FilterInput>,
    /// The resolved chain the filter channel writes eased packed params into
    /// (promoted roots only; snapped to the target by
    /// `resolve_chains`, ordered before this system).
    resolved_filter: Option<&'static mut crate::filters::ResolvedFilterChain>,
    /// The `backdropFilter` channel's target — same live-read rule as
    /// [`Self::filter_input`].
    backdrop_input: Option<&'static crate::filters::BackdropInput>,
    /// The resolved backdrop chain the second filter-channel instance writes
    /// into (projected to the inner chain via `Mut::map_unchanged`).
    resolved_backdrop: Option<&'static mut crate::filters::ResolvedBackdropChain>,
    /// The composite-time 3D transform params on a promoted root; the eased
    /// value lands here and `sync_transform3d_matrices` (PostUpdate) turns
    /// the change into the matrix + composite-only dirt — no dirt push here.
    transform3d: Option<&'static mut crate::layer::transform3d::LayerTransform3d>,
}

/// Advance every transitioning entity toward its [`TransitionInput`] target and
/// write the eased value onto `UiTransform` / `BackgroundColor` / alpha. Runs
/// after `apply_interaction_styles` (and thus after the op drain) so its writes
/// land last in the frame.
pub fn drive_transitions(
    time: Res<Time>,
    mut commands: Commands,
    mut dirt: ResMut<crate::layer::LayerContentDirt>,
    // The filter channel resolves identity padding at retarget time. Both are
    // optional so schedule-only test worlds without asset machinery still
    // drive the scalar channels; a missing pair degrades a chain extension to
    // a discrete swap (see `crate::filters::plan_filter_ease`).
    filter_registry: Option<Res<crate::filters::FilterRegistry>>,
    assets: Option<Res<AssetServer>>,
    mut query: Query<(
        Entity,
        &TransitionInput,
        &mut TransitionState,
        TransitionTargets,
    )>,
) {
    let dt = time.delta_secs();
    for (entity, input, mut state, mut targets) in &mut query {
        // Seed resting values on first sight so a freshly mounted element snaps to
        // its initial style instead of animating in from zero.
        if !state.initialized {
            state
                .translate_x
                .init(input.translate_x.unwrap_or(Length::Px(0.0)));
            state
                .translate_y
                .init(input.translate_y.unwrap_or(Length::Px(0.0)));
            state.scale.init(input.scale.unwrap_or(1.0));
            state.scale_x.init(input.scale_x.unwrap_or(1.0));
            state.scale_y.init(input.scale_y.unwrap_or(1.0));
            state.rotate.init(input.rotate.unwrap_or(0.0));
            state.opacity.init(input.opacity.unwrap_or(1.0));
            if let Some(c) = input.background_color {
                state.color.init(c);
            }
            state.width.init(input.width.unwrap_or(Length::Auto));
            state.height.init(input.height.unwrap_or(Length::Auto));
            state
                .max_width
                .init(input.max_width.unwrap_or(Length::Auto));
            state
                .max_height
                .init(input.max_height.unwrap_or(Length::Auto));
            // Filter: adopt the current wire chain and whatever the resolver
            // produced, so a freshly mounted filtered element snaps instead
            // of fading in from identity.
            state.filter.wire = targets
                .filter_input
                .map(|f| f.0.clone())
                .unwrap_or_default();
            state.filter.current = targets
                .resolved_filter
                .as_deref()
                .map(|c| c.passes.clone())
                .unwrap_or_default();
            state.backdrop_filter.wire = targets
                .backdrop_input
                .map(|f| f.0.clone())
                .unwrap_or_default();
            state.backdrop_filter.current = targets
                .resolved_backdrop
                .as_deref()
                .map(|c| c.0.passes.clone())
                .unwrap_or_default();
            state
                .transform3d
                .init(&input.transform3d.clone().unwrap_or_default());
            state.initialized = true;
        }

        // Imperative bindings win: skip any channel an `{ animated }` wrapper drives.
        let skip_transform = targets.anim.is_some_and(|a| a.0.has_transform());
        let skip_opacity = targets
            .anim
            .is_some_and(|a| a.0.contains(AnimatableProperty::Opacity));
        let skip_bg = targets
            .anim
            .is_some_and(|a| a.0.contains(AnimatableProperty::BackgroundColor));
        // Coarser than its siblings by design: ANY `filter[<i>].<param>`
        // binding parks the WHOLE whole-value filter channel — the channel
        // eases a complete pass list, so there is no per-param seam to merge
        // an imperative writer into. The bindings then re-assert their params
        // on top of the resolver's snap every frame (`AnimationSet::Apply`).
        let skip_filter = targets.anim.is_some_and(|a| a.0.has_filter_params());
        // Same coarse rule for the backdrop channel — independent of the
        // content one (a `backdropFilter[…]` binding parks only backdrop).
        let skip_backdrop = targets.anim.is_some_and(|a| a.0.has_backdrop_params());
        // Any `transform3d.<field>` binding parks the whole channel group,
        // like `filter` (the bindings rebuild the full params struct).
        let skip_transform3d = targets.anim.is_some_and(|a| a.0.has_transform3d());

        // Transform: only when a transform transition is declared; otherwise the
        // static `UiTransform` from `apply_style` stands untouched. Only specified
        // channels are written (passing `None` keeps `build_ui_transform`'s scale
        // precedence intact).
        if input.spec.for_transform().is_some() && !skip_transform {
            let s = input.spec.for_transform();
            let tx = input
                .translate_x
                .map(|t| length_to_val(state.translate_x.drive(t, s, dt)));
            let ty = input
                .translate_y
                .map(|t| length_to_val(state.translate_y.drive(t, s, dt)));
            let sc = input.scale.map(|t| state.scale.drive(t, s, dt));
            let scx = input.scale_x.map(|t| state.scale_x.drive(t, s, dt));
            let scy = input.scale_y.map(|t| state.scale_y.drive(t, s, dt));
            let rot = input.rotate.map(|t| state.rotate.drive(t, s, dt));
            // Compare-before-write so a settled transition doesn't dirty change
            // detection every frame (read via `Deref`, write via `DerefMut`).
            let new = build_ui_transform(tx, ty, sc, scx, scy, rot);
            if *targets.transform != new {
                // Layer-cache classification (see the animation applier): a
                // promoted root's own pure translation is composite-only.
                let translate_only = targets.transform.scale == new.scale
                    && targets.transform.rotation == new.rotation;
                if targets.promoted.is_some() && translate_only {
                    dirt.composite_only.push(entity);
                } else {
                    dirt.nodes.push(entity);
                }
                *targets.transform = new;
            }
        }

        // transform3d: eased field-wise onto the layer's params component;
        // `sync_transform3d_matrices` (PostUpdate) derives the matrix and the
        // composite-only dirt from the change, so no dirt push here. A
        // demoted/never-promoted entity has no component — nothing to drive.
        // Mid-ease unset removes the component with the promotion (snap
        // semantics, like filter's ease-to-empty).
        if input.spec.for_transform3d().is_some()
            && !skip_transform3d
            && let Some(target) = &input.transform3d
            && let Some(t3d) = &mut targets.transform3d
        {
            let new = state
                .transform3d
                .drive(target, input.spec.for_transform3d(), dt);
            // Compare-before-write: a settled ease must not re-trigger the
            // matrix sync's change detection every frame.
            if t3d.0 != new {
                t3d.0 = new;
            }
        }

        // Opacity owns the final alpha across background/text/image. Resolved
        // before the background write so it can be baked into that color —
        // otherwise the two writes would ping-pong the alpha channel every frame
        // and the compare-before-write guards would never settle.
        let alpha = if !skip_opacity && let Some(target) = input.opacity {
            Some(state.opacity.drive(target, input.spec.for_opacity(), dt))
        } else {
            None
        };

        // On a promoted layer root the eased opacity drives the group alpha
        // (below) — colors keep their own alpha, so nothing to bake here. The
        // spring itself always eases, keeping a mid-ease promote/demote
        // continuous.
        let promoted = targets.promoted.is_some();
        if !skip_bg && let Some(target) = input.background_color {
            let mut rgba = state.color.drive(target, input.spec.for_background(), dt);
            if let Some(a) = alpha
                && !promoted
            {
                rgba[3] = a;
            }
            let color = rgba_to_color(rgba);
            match &mut targets.bg {
                Some(c) if c.0 != color => {
                    c.0 = color;
                    dirt.nodes.push(entity);
                }
                Some(_) => {}
                None => {
                    commands.entity(entity).insert(BackgroundColor(color));
                    dirt.nodes.push(entity);
                }
            }
        }

        // Opacity always applies when set (even with no opacity transition: it then
        // snaps), so a transitioning background color doesn't clobber the alpha.
        // Promoted → the group alpha is the single target instead.
        if let Some(alpha) = alpha
            && promoted
        {
            if let Some(la) = &mut targets.layer_alpha
                && la.0 != alpha
            {
                la.0 = alpha;
                // Composite-only: applied to the cached texture at composite
                // time (content of the *enclosing* layer, if any).
                dirt.composite_only.push(entity);
            }
        } else if let Some(alpha) = alpha {
            let mut wrote = false;
            if let Some(c) = &mut targets.bg
                && c.0.alpha() != alpha
            {
                c.0 = c.0.with_alpha(alpha);
                wrote = true;
            }
            if let Some(tc) = &mut targets.text
                && tc.0.alpha() != alpha
            {
                tc.0 = tc.0.with_alpha(alpha);
                wrote = true;
            }
            if let Some(img) = &mut targets.image
                && img.color.alpha() != alpha
            {
                img.color = img.color.with_alpha(alpha);
                wrote = true;
            }
            if wrote {
                dirt.nodes.push(entity);
            }
        }

        // Size (layout): ease the specified `Node` dimensions. Writing `Node`
        // re-triggers Bevy's layout, so each field is compared before writing —
        // a settled transition doesn't force a relayout every frame, and a
        // re-render that reset `Node` to its static style is corrected here.
        // The animations engine never writes `Node`, so no precedence check is
        // needed.
        if input.spec.for_size().is_some()
            && let Some(node) = targets.node.as_mut()
        {
            let s = input.spec.for_size();
            if let Some(t) = input.width {
                let v = length_to_val(state.width.drive(t, s, dt));
                if node.width != v {
                    node.width = v;
                }
            }
            if let Some(t) = input.height {
                let v = length_to_val(state.height.drive(t, s, dt));
                if node.height != v {
                    node.height = v;
                }
            }
            if let Some(t) = input.max_width {
                let v = length_to_val(state.max_width.drive(t, s, dt));
                if node.max_width != v {
                    node.max_width = v;
                }
            }
            if let Some(t) = input.max_height {
                let v = length_to_val(state.max_height.drive(t, s, dt));
                if node.max_height != v {
                    node.max_height = v;
                }
            }
        }

        // Filter: ease the promoted root's resolved chain between wire
        // targets (see [`FilterChannel::drive`] for the retarget/writer
        // contract). A write is composite-only dirt, like the resolver's.
        if !skip_filter
            && state.filter.drive(
                targets.filter_input.map(|f| &f.0),
                targets.resolved_filter.as_mut().map(Mut::reborrow),
                input.spec.for_filter(),
                filter_registry.as_deref(),
                assets.as_deref(),
                dt,
            )
        {
            dirt.composite_only.push(entity);
        }

        // Backdrop filter: the second instance of the same channel, over the
        // backdrop component pair (targets projected to the shared inner
        // types). A write is composite-only dirt like the content one.
        if !skip_backdrop
            && state.backdrop_filter.drive(
                targets.backdrop_input.map(|f| &f.0),
                targets
                    .resolved_backdrop
                    .as_mut()
                    .map(|m| m.reborrow().map_unchanged(|b| &mut b.0)),
                input.spec.for_backdrop_filter(),
                filter_registry.as_deref(),
                assets.as_deref(),
                dt,
            )
        {
            dirt.composite_only.push(entity);
        }
    }
}

fn color_to_rgba(color: Color) -> [f32; 4] {
    let s = color.to_srgba();
    [s.red, s.green, s.blue, s.alpha]
}

fn rgba_to_color(rgba: [f32; 4]) -> Color {
    Color::srgba(rgba[0], rgba[1], rgba[2], rgba[3])
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::animations::AnimatedBindings;
    use std::time::Duration;

    fn timing(duration: f32, easing: Easing) -> ChannelTransition {
        ChannelTransition {
            duration: Some(WireTime::from_secs(duration)),
            easing,
            delay: WireTime::from_secs(0.0),
            stiffness: None,
            damping: None,
            mass: 1.0,
        }
    }

    fn parse<T: serde::de::DeserializeOwned>(json: serde_json::Value) -> T {
        serde_json::from_value(json).expect("valid json")
    }

    #[test]
    fn channel_resolution_falls_back_to_all() {
        let t: Transition = parse(serde_json::json!({
            "all": { "duration": 100 },
            "opacity": { "duration": 200 },
        }));
        // `opacity` has its own entry; `transform`/`background` fall back to `all`.
        // The wire numbers are milliseconds → seconds (200ms → 0.2s, 100ms → 0.1s).
        let secs = |c: &ChannelTransition| c.duration.map(WireTime::seconds);
        assert!(t.for_opacity().is_some());
        assert_eq!(secs(t.for_opacity().unwrap()), Some(0.2));
        assert_eq!(secs(t.for_transform().unwrap()), Some(0.1));
        assert_eq!(secs(t.for_background().unwrap()), Some(0.1));

        // No `all`: an unspecified channel has no transition.
        let t: Transition = parse(serde_json::json!({ "opacity": { "duration": 50 } }));
        assert!(t.for_transform().is_none());
        assert!(t.for_opacity().is_some());
    }

    /// The filter channel resolves like its siblings: explicit entry first,
    /// else `all`, else none.
    #[test]
    fn filter_channel_falls_back_to_all() {
        let secs = |c: &ChannelTransition| c.duration.map(WireTime::seconds);
        let t: Transition = parse(serde_json::json!({
            "all": { "duration": 100 },
            "filter": { "duration": 400 },
        }));
        assert_eq!(secs(t.for_filter().unwrap()), Some(0.4));

        let t: Transition = parse(serde_json::json!({ "all": { "duration": 100 } }));
        assert_eq!(secs(t.for_filter().unwrap()), Some(0.1));

        let t: Transition = parse(serde_json::json!({ "opacity": { "duration": 50 } }));
        assert!(t.for_filter().is_none());
    }

    #[test]
    fn to_driver_selects_spring_or_timing() {
        let spring = ChannelTransition {
            duration: None,
            easing: Easing::Linear,
            delay: WireTime::from_secs(0.0),
            stiffness: Some(120.0),
            damping: Some(14.0),
            mass: 1.0,
        };
        assert!(matches!(spring.to_driver(1.0), Driver::Spring { .. }));
        assert!(matches!(
            timing(0.3, Easing::Linear).to_driver(1.0),
            Driver::Timing { .. }
        ));
        // A delay wraps the timing in a Delay driver.
        let delayed = ChannelTransition {
            delay: WireTime::from_secs(0.2),
            ..timing(0.3, Easing::Linear)
        };
        assert!(matches!(delayed.to_driver(1.0), Driver::Delay { .. }));
    }

    #[test]
    fn channel_snaps_without_spec_and_eases_with_one() {
        // No spec → snap straight to target.
        let mut ch = Channel::default();
        ch.init(1.0);
        assert_eq!(ch.drive(0.5, None, 0.016), 0.5);

        // With a 1s linear timing → halfway after 0.5s.
        let mut ch = Channel::default();
        ch.init(1.0);
        let spec = timing(1.0, Easing::Linear);
        ch.drive(0.0, Some(&spec), 0.0); // arm; no time elapsed yet
        let v = ch.drive(0.0, Some(&spec), 0.5); // same target, advance 0.5s
        assert!((v - 0.5).abs() < 1e-3, "halfway expected ~0.5, got {v}");
        let v = ch.drive(0.0, Some(&spec), 0.5);
        assert!((v - 0.0).abs() < 1e-3, "end expected 0, got {v}");
        assert!(ch.runner.is_none(), "runner dropped once finished");
    }

    #[test]
    fn color_channel_lerps_to_target() {
        let mut c = ProgressChannel::<[f32; 4]>::default();
        c.init([0.0, 0.0, 0.0, 1.0]);
        let spec = timing(1.0, Easing::Linear);
        c.drive([1.0, 0.5, 0.0, 1.0], Some(&spec), 0.0); // arm
        let mid = c.drive([1.0, 0.5, 0.0, 1.0], Some(&spec), 0.5);
        assert!((mid[0] - 0.5).abs() < 1e-3);
        assert!((mid[1] - 0.25).abs() < 1e-3);
        assert!((mid[2] - 0.0).abs() < 1e-3);
    }

    /// Build a one-entity world running `drive_transitions`, advancing `Time`.
    fn drive_world() -> (World, Schedule) {
        let mut world = World::new();
        world.init_resource::<crate::layer::LayerContentDirt>();
        world.insert_resource(Time::<()>::default());
        let mut schedule = Schedule::default();
        schedule.add_systems(drive_transitions);
        (world, schedule)
    }

    fn advance(world: &mut World, secs: f32) {
        world
            .resource_mut::<Time>()
            .advance_by(Duration::from_secs_f32(secs));
    }

    #[test]
    fn system_eases_scale_on_press_then_release() {
        let (mut world, mut schedule) = drive_world();
        let spec = Transition {
            transform: Some(timing(1.0, Easing::Linear)),
            ..Default::default()
        };
        let e = world
            .spawn((
                TransitionInput {
                    spec: spec.clone(),
                    scale: Some(1.0),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
            ))
            .id();

        // First frame seeds the resting state — scale snaps to 1, no animation.
        schedule.run(&mut world);
        assert_eq!(world.entity(e).get::<UiTransform>().unwrap().scale.x, 1.0);

        // Press: target 0.95. Halfway through a 1s ease → ~0.975.
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .scale = Some(0.95);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let sx = world.entity(e).get::<UiTransform>().unwrap().scale.x;
        assert!(
            (sx - 0.975).abs() < 1e-2,
            "mid-press expected ~0.975, got {sx}"
        );

        // Finish the press ease.
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let sx = world.entity(e).get::<UiTransform>().unwrap().scale.x;
        assert!((sx - 0.95).abs() < 1e-3, "pressed expected 0.95, got {sx}");

        // Release back to 1.0, eases again.
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .scale = Some(1.0);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let sx = world.entity(e).get::<UiTransform>().unwrap().scale.x;
        assert!(
            (sx - 0.975).abs() < 1e-2,
            "mid-release expected ~0.975, got {sx}"
        );
    }

    /// `transition.transform3d` eases the layer's params field-wise; without a
    /// spec the write snaps; perspective snaps when the previous target was
    /// orthographic; a demoted entity (no `LayerTransform3d`) is a no-op.
    #[test]
    fn system_eases_transform3d() {
        use crate::layer::transform3d::LayerTransform3d;
        use crate::protocol::Transform3d;

        let (mut world, mut schedule) = drive_world();
        let spec = Transition {
            transform3d: Some(timing(1.0, Easing::Linear)),
            ..Default::default()
        };
        let base = Transform3d::default();
        let e = world
            .spawn((
                TransitionInput {
                    spec: spec.clone(),
                    transform3d: Some(base.clone()),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
                LayerTransform3d(base.clone()),
            ))
            .id();

        // First frame seeds resting state: identity, no ease-in from nowhere.
        schedule.run(&mut world);
        let t = world.entity(e).get::<LayerTransform3d>().unwrap().0.clone();
        assert!(t.is_identity());

        // Retarget rotateY 90° (+ a perspective from an orthographic start —
        // that channel snaps while the rotation eases).
        let target = Transform3d {
            rotate_y: Some(crate::protocol::Animatable::Static(
                crate::protocol::Angle::from_radians(std::f32::consts::FRAC_PI_2),
            )),
            perspective: Some(crate::protocol::Animatable::Static(800.0)),
            ..Default::default()
        };
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .transform3d = Some(target.clone());
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let t = world.entity(e).get::<LayerTransform3d>().unwrap().0.clone();
        let ry = t.rotate_y.static_val().unwrap().radians();
        assert!(
            (ry - std::f32::consts::FRAC_PI_4).abs() < 0.05,
            "mid-ease expected ~45°, got {}°",
            ry.to_degrees()
        );
        assert_eq!(
            t.perspective.static_val(),
            Some(800.0),
            "ortho→perspective snaps"
        );

        // Finish the ease.
        advance(&mut world, 0.6);
        schedule.run(&mut world);
        let t = world.entity(e).get::<LayerTransform3d>().unwrap().0.clone();
        assert!(
            (t.rotate_y.static_val().unwrap().radians() - std::f32::consts::FRAC_PI_2).abs() < 1e-3
        );

        // No spec → snap. (Fresh entity, `all`-less spec without transform3d.)
        let e2 = world
            .spawn((
                TransitionInput {
                    spec: Transition {
                        opacity: Some(timing(1.0, Easing::Linear)),
                        ..Default::default()
                    },
                    transform3d: Some(target.clone()),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
                LayerTransform3d(base),
            ))
            .id();
        schedule.run(&mut world);
        // Without a transform3d (or `all`) spec the drive block never runs —
        // the static style applier owns the component (stays at `base` here,
        // since this harness has no style apply).
        let t2 = world
            .entity(e2)
            .get::<LayerTransform3d>()
            .unwrap()
            .0
            .clone();
        assert!(t2.is_identity());

        // Demoted entity (no LayerTransform3d): driving is a no-op, no panic.
        let e3 = world
            .spawn((
                TransitionInput {
                    spec,
                    transform3d: Some(target.clone()),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
            ))
            .id();
        advance(&mut world, 0.1);
        schedule.run(&mut world);
        assert!(world.entity(e3).get::<LayerTransform3d>().is_none());
    }

    #[test]
    fn system_eases_percent_translate() {
        let (mut world, mut schedule) = drive_world();
        let spec = Transition {
            transform: Some(timing(1.0, Easing::Linear)),
            ..Default::default()
        };
        let e = world
            .spawn((
                TransitionInput {
                    spec,
                    translate_x: Some(Length::Percent(0.0)),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
            ))
            .id();

        // First frame seeds the resting state at 0% — snaps, no animation.
        schedule.run(&mut world);
        assert_eq!(
            world.entity(e).get::<UiTransform>().unwrap().translation.x,
            Val::Percent(0.0)
        );

        // Retarget to 100%: halfway through a 1s linear ease → ~50%, still in
        // percent units (not collapsed to px).
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .translate_x = Some(Length::Percent(100.0));
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let tx = world.entity(e).get::<UiTransform>().unwrap().translation.x;
        assert!(
            matches!(tx, Val::Percent(v) if (v - 50.0).abs() < 1.0),
            "mid expected ~50%, got {tx:?}"
        );

        advance(&mut world, 0.5);
        schedule.run(&mut world);
        assert_eq!(
            world.entity(e).get::<UiTransform>().unwrap().translation.x,
            Val::Percent(100.0)
        );
    }

    #[test]
    fn animated_style_channel_wins_over_transition() {
        let (mut world, mut schedule) = drive_world();
        let spec = Transition {
            transform: Some(timing(1.0, Easing::Linear)),
            ..Default::default()
        };
        // The entity also has an AnimatedNode binding for scale → transition must
        // not touch the transform (the imperative path owns it).
        let bindings = AnimatedBindings(
            [(
                crate::animations::AnimatableProperty::Scale,
                crate::animations::protocol::Binding::Shared { id: 1 },
            )]
            .into(),
        );
        let e = world
            .spawn((
                TransitionInput {
                    spec,
                    scale: Some(1.0),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::from_scale(Vec2::splat(2.0)), // a value the imperative path "set"
                AnimatedNode(bindings),
            ))
            .id();

        schedule.run(&mut world);
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .scale = Some(0.95);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        // Untouched by the transition: still the imperative 2.0.
        assert_eq!(world.entity(e).get::<UiTransform>().unwrap().scale.x, 2.0);
    }

    /// A `filter[<i>].<param>` binding parks the WHOLE whole-value filter
    /// channel (`skip_filter`): on a filter retarget the transition must not
    /// touch the resolved chain — the per-param binding (the animations
    /// applier) owns it. A control entity without the binding shows the
    /// channel would otherwise write.
    #[test]
    fn filter_param_binding_gates_filter_transition() {
        use crate::animations::ValueKind;
        use std::sync::Arc;

        let (mut world, mut schedule) = drive_world();
        let spec = Transition {
            filter: Some(timing(1.0, Easing::Linear)),
            ..Default::default()
        };
        let pass = |amount: f32| crate::filters::ResolvedFilterPass {
            shader: Handle::default(),
            params: vec![Vec4::new(amount, 0.0, 0.0, 0.0)],
            layout: Arc::from(vec![crate::filters::ParamSlot {
                name: "amount",
                kind: ValueKind::Scalar,
                vec: 0,
                comp: 0,
                len: 1,
            }]),
            wire_index: 0,
        };
        let wire = |amount: f32| -> crate::filters::FilterChain {
            serde_json::from_value(serde_json::json!(
                { "name": "grayscale", "params": { "amount": amount } }
            ))
            .unwrap()
        };
        let chain = |amount: f32| crate::filters::ResolvedFilterChain {
            passes: vec![pass(amount)],
            outset_px: 0,
            always_dirty: false,
            version: 1,
            scale: 1.0,
        };
        let bindings = AnimatedBindings(
            [(
                crate::animations::AnimatableProperty::FilterParam {
                    index: 0,
                    name: "amount".into(),
                },
                crate::animations::protocol::Binding::Shared { id: 1 },
            )]
            .into(),
        );

        let spawn = |world: &mut World, gated: bool| {
            let mut e = world.spawn((
                TransitionInput {
                    spec: spec.clone(),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
                crate::filters::FilterInput(wire(0.0)),
                chain(0.0),
            ));
            if gated {
                e.insert(AnimatedNode(bindings.clone()));
            }
            e.id()
        };
        let gated = spawn(&mut world, true);
        let control = spawn(&mut world, false);

        // Seed frame: both channels adopt the current wire chain + passes.
        schedule.run(&mut world);

        // Retarget: stamp the new wire chain and simulate the resolver's
        // same-frame snap of the component to the target.
        for e in [gated, control] {
            *world
                .entity_mut(e)
                .get_mut::<crate::filters::FilterInput>()
                .unwrap() = crate::filters::FilterInput(wire(1.0));
            let mut em = world.entity_mut(e);
            let mut c = em.get_mut::<crate::filters::ResolvedFilterChain>().unwrap();
            c.passes = vec![pass(1.0)];
            c.version = 2;
        }
        advance(&mut world, 0.1);
        schedule.run(&mut world);

        // Control: the channel armed a matched ease over the snap and wrote
        // a mid-ease value — proving the channel was live.
        let c = world
            .entity(control)
            .get::<crate::filters::ResolvedFilterChain>()
            .unwrap();
        let w = c.passes[0].params[0].x;
        assert!(
            w > 0.0 && w < 1.0,
            "control: transition eased over the snap, got {w}"
        );
        assert_eq!(c.version, 3, "control: transition bumped the version");

        // Gated: `skip_filter` — the snapped chain is untouched.
        let c = world
            .entity(gated)
            .get::<crate::filters::ResolvedFilterChain>()
            .unwrap();
        assert_eq!(
            c.passes[0].params[0].x, 1.0,
            "gated: the transition must not touch the chain"
        );
        assert_eq!(c.version, 2, "gated: version stays the resolver's");
    }

    /// Once a transition has settled, `drive_transitions` must stop marking the
    /// target components changed (compare-before-write) — a settled hover/press
    /// style shouldn't keep transform propagation / extraction hot forever.
    #[test]
    fn settled_transition_does_not_dirty_components() {
        #[derive(Resource, Default)]
        struct Dirty(usize);

        let (mut world, mut schedule) = drive_world();
        world.init_resource::<Dirty>();
        let spec = Transition {
            transform: Some(timing(0.2, Easing::Linear)),
            background_color: Some(timing(0.2, Easing::Linear)),
            opacity: Some(timing(0.2, Easing::Linear)),
            ..Default::default()
        };
        let e = world
            .spawn((
                TransitionInput {
                    spec,
                    scale: Some(1.0),
                    // Deliberately different from the bg target's alpha: opacity
                    // owns the final alpha, and the two writes must still settle.
                    opacity: Some(0.5),
                    background_color: Some([1.0, 0.0, 0.0, 1.0]),
                    ..Default::default()
                },
                TransitionState::default(),
                UiTransform::default(),
                BackgroundColor(Color::WHITE),
            ))
            .id();

        type AnyTargetChanged = Or<(Changed<UiTransform>, Changed<BackgroundColor>)>;

        let mut detect = Schedule::default();
        detect.add_systems(|q: Query<(), AnyTargetChanged>, mut dirty: ResMut<Dirty>| {
            dirty.0 = q.iter().count();
        });

        // Seed, retarget, and run the ease well past completion.
        schedule.run(&mut world);
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .scale = Some(0.9);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        detect.run(&mut world); // consume all the churn so far

        advance(&mut world, 0.5);
        schedule.run(&mut world);
        detect.run(&mut world);
        assert_eq!(
            world.resource::<Dirty>().0,
            0,
            "a settled transition must not dirty anything"
        );
    }

    #[test]
    fn lerp_length_same_unit_else_snaps() {
        assert_eq!(Length::Px(0.0).lerp(Length::Px(10.0), 0.5), Length::Px(5.0));
        assert_eq!(
            Length::Percent(0.0).lerp(Length::Percent(100.0), 0.25),
            Length::Percent(25.0)
        );
        // `auto` or mixed units can't be interpolated → snap to the target.
        assert_eq!(Length::Auto.lerp(Length::Px(10.0), 0.5), Length::Px(10.0));
        assert_eq!(
            Length::Px(0.0).lerp(Length::Percent(10.0), 0.5),
            Length::Percent(10.0)
        );
    }

    fn px(l: Length) -> f32 {
        match l {
            Length::Px(v) => v,
            other => panic!("expected Px, got {other:?}"),
        }
    }

    #[test]
    fn length_channel_eases_then_idles() {
        let mut ch = ProgressChannel::<Length>::default();
        ch.init(Length::Px(0.0));
        let spec = timing(1.0, Easing::Linear);
        // Arm toward 100; the arm frame reports the (still 0) value.
        assert!((px(ch.drive(Length::Px(100.0), Some(&spec), 0.0)) - 0.0).abs() < 1e-3);
        assert!((px(ch.drive(Length::Px(100.0), Some(&spec), 0.5)) - 50.0).abs() < 1e-3);
        assert!((px(ch.drive(Length::Px(100.0), Some(&spec), 0.5)) - 100.0).abs() < 1e-3);
        // Settled and target unchanged → idle: the runner is dropped and the
        // reading holds steady (the caller's compare skips the `Node` write).
        assert!(ch.runner.is_none(), "runner dropped once settled");
        assert_eq!(
            ch.drive(Length::Px(100.0), Some(&spec), 0.5),
            Length::Px(100.0)
        );
    }

    #[test]
    fn system_eases_max_height_layout() {
        let (mut world, mut schedule) = drive_world();
        let spec = Transition {
            size: Some(timing(1.0, Easing::Linear)),
            ..Default::default()
        };
        let e = world
            .spawn((
                TransitionInput {
                    spec,
                    max_height: Some(Length::Px(120.0)),
                    ..Default::default()
                },
                TransitionState::default(),
                Node::default(),
                UiTransform::default(),
            ))
            .id();

        // First frame seeds the resting state (120) without writing Node.
        schedule.run(&mut world);

        // Collapse to 0: halfway through a 1s ease → ~60.
        world
            .entity_mut(e)
            .get_mut::<TransitionInput>()
            .unwrap()
            .max_height = Some(Length::Px(0.0));
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let mh = world.entity(e).get::<Node>().unwrap().max_height;
        assert!(
            matches!(mh, Val::Px(v) if (v - 60.0).abs() < 1.0),
            "mid expected ~60px, got {mh:?}"
        );

        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let mh = world.entity(e).get::<Node>().unwrap().max_height;
        assert!(
            matches!(mh, Val::Px(v) if v.abs() < 1e-3),
            "settled expected 0px, got {mh:?}"
        );
    }

    /// `drive_scroll_transition` eases `ScrollPosition` toward the state's target
    /// (seeded at the live offset on first sight) and settles exactly on it.
    #[test]
    fn system_eases_scroll_toward_target() {
        let mut world = World::new();
        world.init_resource::<crate::layer::LayerContentDirt>();
        world.insert_resource(Time::<()>::default());
        let mut schedule = Schedule::default();
        schedule.add_systems(drive_scroll_transition);

        let e = world
            .spawn((
                ScrollTransitionInput(timing(1.0, Easing::Linear)),
                ScrollTransitionState::default(),
                ScrollPosition::default(),
            ))
            .id();

        // First frame seeds resting state at the live offset (0) — no movement.
        schedule.run(&mut world);
        assert_eq!(
            world.entity(e).get::<ScrollPosition>().unwrap().0,
            Vec2::ZERO
        );

        // Target y=100; halfway through a 1s linear ease → ~50.
        world
            .entity_mut(e)
            .get_mut::<ScrollTransitionState>()
            .unwrap()
            .target = Vec2::new(0.0, 100.0);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let y = world.entity(e).get::<ScrollPosition>().unwrap().0.y;
        assert!((y - 50.0).abs() < 1.0, "mid-ease expected ~50, got {y}");

        // Finish the ease → exactly 100.
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        assert_eq!(
            world.entity(e).get::<ScrollPosition>().unwrap().0,
            Vec2::new(0.0, 100.0)
        );
    }

    /// A direct external write to `ScrollPosition` mid-ease (the scrollbar widget's
    /// thumb-drag and track-click paging write the offset directly) snaps: the
    /// written value survives exactly and nothing eases back toward the stale target.
    #[test]
    fn scroll_direct_write_snaps_the_ease() {
        let mut world = World::new();
        world.init_resource::<crate::layer::LayerContentDirt>();
        world.insert_resource(Time::<()>::default());
        let mut schedule = Schedule::default();
        schedule.add_systems(drive_scroll_transition);

        let e = world
            .spawn((
                ScrollTransitionInput(timing(1.0, Easing::Linear)),
                ScrollTransitionState::default(),
                ScrollPosition::default(),
            ))
            .id();
        schedule.run(&mut world); // seed resting state at 0

        // Leave an ease mid-flight toward y=100.
        world
            .entity_mut(e)
            .get_mut::<ScrollTransitionState>()
            .unwrap()
            .target = Vec2::new(0.0, 100.0);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let y = world.entity(e).get::<ScrollPosition>().unwrap().0.y;
        assert!(y > 0.0 && y < 100.0, "mid-ease expected, got {y}");

        // The widget writes the offset directly: the value must survive as-is...
        world.entity_mut(e).get_mut::<ScrollPosition>().unwrap().0 = Vec2::new(0.0, 42.0);
        advance(&mut world, 0.25);
        schedule.run(&mut world);
        assert_eq!(
            world.entity(e).get::<ScrollPosition>().unwrap().0,
            Vec2::new(0.0, 42.0)
        );
        // ...and stay put on later frames (target adopted, runners dropped).
        advance(&mut world, 0.25);
        schedule.run(&mut world);
        assert_eq!(
            world.entity(e).get::<ScrollPosition>().unwrap().0,
            Vec2::new(0.0, 42.0)
        );
    }

    /// `snap_to` (what `bridge_scrollbar_capture` calls each drag frame) parks a
    /// mid-flight ease at the live offset: the stale target stops mattering.
    #[test]
    fn scroll_snap_to_parks_a_mid_flight_ease() {
        let mut world = World::new();
        world.init_resource::<crate::layer::LayerContentDirt>();
        world.insert_resource(Time::<()>::default());
        let mut schedule = Schedule::default();
        schedule.add_systems(drive_scroll_transition);

        let e = world
            .spawn((
                ScrollTransitionInput(timing(1.0, Easing::Linear)),
                ScrollTransitionState::default(),
                ScrollPosition::default(),
            ))
            .id();
        schedule.run(&mut world); // seed resting state at 0

        world
            .entity_mut(e)
            .get_mut::<ScrollTransitionState>()
            .unwrap()
            .target = Vec2::new(0.0, 100.0);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        let live = world.entity(e).get::<ScrollPosition>().unwrap().0;
        assert!(
            live.y > 0.0 && live.y < 100.0,
            "mid-ease expected, got {live:?}"
        );

        world
            .entity_mut(e)
            .get_mut::<ScrollTransitionState>()
            .unwrap()
            .snap_to(live);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        assert_eq!(world.entity(e).get::<ScrollPosition>().unwrap().0, live);
        advance(&mut world, 0.5);
        schedule.run(&mut world);
        assert_eq!(world.entity(e).get::<ScrollPosition>().unwrap().0, live);
    }
}