waft-widgets 0.6.0

Widget framework and widgets for Waft
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
//! Flutter counterpart: `widgets/scrollable.dart`.

use std::any::TypeId;
use std::fmt::{self, Debug};
use std::rc::Rc;
use std::time::Duration;

use waft_animation::Curve;
use waft_embedder::{Clip, Offset};
use waft_foundation::{App, CompleterFuture, Handle, HandleId, Listener, OptionRetained, wait_all};
use waft_gestures::{
    DeviceGestureSettings, Drag, DragDownDetails, DragEndDetails, DragGestureRecognizer,
    DragStartBehavior, DragStartDetails, DragUpdateDetails, GestureBinding,
    HorizontalDragGestureRecognizer, PointerEvent, VerticalDragGestureRecognizer,
};
use waft_painting::{
    Axis, AxisDirection, axis_direction_is_reversed, axis_direction_to_axis, flip_axis,
};
use waft_rendering::{AnyRenderObject, HitTestBehavior, RenderIgnorePointer, ViewportOffsetRef};
use waft_scheduler::{Ticker, TickerCallback, TickerProvider, TickerProviderObject};
use waft_services::{HardwareKeyboard, RestorationBucket, RestorationData, RestorationManager};

use crate::framework::{
    BuildContext, GlobalKey, InheritedWidget, IntoWidget, KeyRef, State, StateData, StatefulWidget,
    WidgetRef,
};
use crate::view::View;
use crate::widgets::basic::{IgnorePointer, Listener as PointerListener};
use crate::widgets::gesture_detector::{
    GestureRecognizerFactories, GestureRecognizerFactory, GestureRecognizerFactoryWithHandlers,
    RawGestureDetector, RawGestureDetectorState,
};
use crate::widgets::media_query::MediaQuery;
use crate::widgets::restoration::{
    RestorableProperty, RestorablePropertyData, RestorationMixin, RestorationMixinData,
};
use crate::widgets::restoration_properties::{RestorableValue, RestorableValueData};
use crate::widgets::scroll_activity::ScrollHoldController;
use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
use crate::widgets::scroll_context::ScrollContext;
use crate::widgets::scroll_controller::{
    ScrollController, ScrollControllerLeaf, ScrollControllerRef,
};
use crate::widgets::scroll_physics::ScrollPhysicsRef;
use crate::widgets::scroll_position::{
    AnyScrollPosition, ScrollPositionAlignmentPolicy, ScrollPositionRef,
};
use crate::widgets::scrollable_helpers::{ScrollIncrementCalculator, ScrollableDetails};
use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
use waft_foundation::Ref;

/// Signature used by [`Scrollable`] to build the viewport through which the
/// scrollable content is displayed.
pub type ViewportBuilder = Rc<dyn Fn(&mut App, BuildContext, ViewportOffsetRef) -> WidgetRef>;

// The return type of `perform_ensure_visible`.
//
// The list of futures represents each pending ScrollPosition call to
// ensure_visible. The returned ScrollableState's context is used to find the
// next potential ancestor Scrollable.
type EnsureVisibleResults = (Vec<CompleterFuture<()>>, Handle<ScrollableState>);

/// A widget that manages scrolling in one dimension and informs the `Viewport`
/// through which the content is viewed.
///
/// [`Scrollable`] implements the interaction model for a scrollable widget,
/// including gesture recognition, but does not have an opinion about how the
/// viewport, which actually displays the children, is constructed.
///
/// It's rare to construct a [`Scrollable`] directly. Instead, consider `ListView`
/// or `GridView`, which combine scrolling, viewporting, and a layout model.
///
/// The static [`Scrollable::of`] and [`Scrollable::ensure_visible`] functions are
/// often used to interact with the [`Scrollable`] widget inside a `ListView` or
/// a `GridView`.
///
/// To further customize scrolling behavior with a [`Scrollable`]:
///
/// 1. You can provide a [`viewport_builder`](Self::viewport_builder) to customize the child
///    model.
///
/// 2. You can provide a custom `ScrollController` that creates a custom
///    [`ScrollPosition`](crate::ScrollPosition).
///
/// ## Persisting the scroll position during a session
///
/// Scrollables attempt to persist their scroll position using `PageStorage`.
/// This can be disabled by setting `ScrollController.keepScrollOffset` to false
/// on the [`controller`](Self::controller).
pub struct Scrollable {
    pub key: Option<KeyRef>,

    /// The direction in which this widget scrolls.
    ///
    /// For example, if the [`axis_direction`](Self::axis_direction) is
    /// [`AxisDirection::Down`], increasing the scroll position will cause content below the
    /// bottom of the viewport to become visible through the viewport. Similarly, if the axis
    /// direction is [`AxisDirection::Right`], increasing the scroll position will cause
    /// content beyond the right edge of the viewport to become visible through the viewport.
    ///
    /// Defaults to [`AxisDirection::Down`].
    pub axis_direction: AxisDirection,

    /// An object that can be used to control the position to which this widget is
    /// scrolled.
    ///
    /// A `ScrollController` serves several purposes. It can be used to control
    /// the initial scroll position, whether the scroll view should automatically
    /// save and restore its scroll position in the `PageStorage`, to read the current
    /// scroll position, or change it.
    ///
    /// If `None`, a `ScrollController` will be created internally by [`Scrollable`]
    /// in order to create and manage the [`ScrollPosition`](crate::ScrollPosition).
    pub controller: Option<ScrollControllerRef>,

    /// How the widgets should respond to user input.
    ///
    /// For example, determines how the widget continues to animate after the
    /// user stops dragging the scroll view.
    ///
    /// Defaults to matching platform conventions via the physics provided from
    /// the ambient [`ScrollConfiguration`].
    ///
    /// If an explicit [`ScrollBehaviorRef`] is provided to
    /// [`scroll_behavior`](Self::scroll_behavior), the [`ScrollPhysics`](crate::ScrollPhysics) provided by that
    /// behavior will take precedence after this one.
    ///
    /// The physics can be changed dynamically, but new physics will only take
    /// effect if the _type_ of the provided object changes.
    pub physics: Option<ScrollPhysicsRef>,

    /// Builds the viewport through which the scrollable content is displayed.
    ///
    /// A typical viewport uses the given [`AnyViewportOffset`] to determine which part
    /// of its content is actually visible through the viewport.
    pub viewport_builder: ViewportBuilder,

    /// An optional function that will be called to calculate the distance to
    /// scroll when the scrollable is asked to scroll via the keyboard using a
    /// [`crate::ScrollAction`].
    ///
    /// If `None`, the default for [`crate::ScrollIncrementType::Page`] is 80% of the size of
    /// the scroll window, and for [`crate::ScrollIncrementType::Line`], 50 logical pixels.
    pub increment_calculator: Option<ScrollIncrementCalculator>,

    /// Defines the behavior of the gesture detector used in this [`Scrollable`].
    ///
    /// This defaults to [`HitTestBehavior::Opaque`] which means it prevents targets
    /// behind this [`Scrollable`] from receiving events.
    pub hit_test_behavior: HitTestBehavior,

    /// Determines the way that drag start behavior is handled.
    ///
    /// If set to [`DragStartBehavior::Start`], scrolling drag behavior will
    /// begin at the position where the drag gesture won the arena. If set to
    /// [`DragStartBehavior::Down`] it will begin at the position where a down
    /// event is first detected.
    ///
    /// By default, the drag start behavior is [`DragStartBehavior::Start`].
    pub drag_start_behavior: DragStartBehavior,

    /// Restoration ID to save and restore the scroll offset of the scrollable.
    ///
    /// If a restoration id is provided, the scrollable will persist its current
    /// scroll offset and restore it during state restoration.
    ///
    /// The scroll offset is persisted in a [`RestorationBucket`] claimed from
    /// the surrounding `RestorationScope` using the provided restoration ID.
    pub restoration_id: Option<String>,

    /// A [`ScrollBehaviorRef`] that will be applied to this widget individually.
    ///
    /// Defaults to `None`, wherein the inherited behavior is copied and
    /// modified to alter the viewport decoration.
    ///
    /// A behavior also provides [`ScrollPhysics`](crate::ScrollPhysics). If an explicit physics is provided in
    /// [`physics`](Self::physics), it will take precedence, followed by this behavior, and
    /// then the inherited ancestor behavior.
    pub scroll_behavior: Option<ScrollBehaviorRef>,

    /// The clip a decorator should honour.
    ///
    /// Defaults to [`Clip::HardEdge`].
    ///
    /// This is passed to decorators in [`ScrollableDetails`], and does not directly affect
    /// clipping of the [`Scrollable`].
    pub clip_behavior: Clip,
}

impl Scrollable {
    /// Creates a widget that scrolls.
    pub fn new(viewport_builder: ViewportBuilder) -> Scrollable {
        Scrollable {
            key: None,
            axis_direction: AxisDirection::Down,
            controller: None,
            physics: None,
            viewport_builder,
            increment_calculator: None,
            hit_test_behavior: HitTestBehavior::Opaque,
            drag_start_behavior: DragStartBehavior::Start,
            restoration_id: None,
            scroll_behavior: None,
            clip_behavior: Clip::HardEdge,
        }
    }

    /// Dart `Scrollable(key:)`.
    pub fn key(mut self, key: KeyRef) -> Scrollable {
        self.key = Some(key);
        self
    }

    /// Dart `Scrollable(axisDirection:)`.
    pub fn axis_direction(mut self, axis_direction: AxisDirection) -> Scrollable {
        self.axis_direction = axis_direction;
        self
    }

    /// Dart `Scrollable(controller:)`.
    pub fn controller(mut self, controller: ScrollControllerRef) -> Scrollable {
        self.controller = Some(controller);
        self
    }

    /// Dart `Scrollable(physics:)`.
    pub fn physics(mut self, physics: ScrollPhysicsRef) -> Scrollable {
        self.physics = Some(physics);
        self
    }

    /// Dart `Scrollable(incrementCalculator:)`.
    pub fn increment_calculator(
        mut self,
        increment_calculator: ScrollIncrementCalculator,
    ) -> Scrollable {
        self.increment_calculator = Some(increment_calculator);
        self
    }

    /// Dart `Scrollable(hitTestBehavior:)`.
    pub fn hit_test_behavior(mut self, hit_test_behavior: HitTestBehavior) -> Scrollable {
        self.hit_test_behavior = hit_test_behavior;
        self
    }

    /// Dart `Scrollable(dragStartBehavior:)`.
    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> Scrollable {
        self.drag_start_behavior = drag_start_behavior;
        self
    }

    /// Dart `Scrollable(restorationId:)`.
    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> Scrollable {
        self.restoration_id = Some(restoration_id.into());
        self
    }

    /// Dart `Scrollable(scrollBehavior:)`.
    pub fn scroll_behavior(mut self, scroll_behavior: ScrollBehaviorRef) -> Scrollable {
        self.scroll_behavior = Some(scroll_behavior);
        self
    }

    /// Dart `Scrollable(clipBehavior:)`.
    pub fn clip_behavior(mut self, clip_behavior: Clip) -> Scrollable {
        self.clip_behavior = clip_behavior;
        self
    }

    /// The axis along which the scroll view scrolls.
    ///
    /// Determined by the [`axis_direction`](Self::axis_direction).
    pub fn axis(&self) -> Axis {
        axis_direction_to_axis(self.axis_direction)
    }

    /// The state from the closest instance of this class that encloses the given
    /// context, or `None` if none is found.
    ///
    /// Calling this method will create a dependency on the [`ScrollableState`]
    /// that is returned, if there is one. This is typically the closest
    /// [`Scrollable`], but may be a more distant ancestor if `axis` is used to
    /// target a specific [`Scrollable`].
    ///
    /// Using the optional [`Axis`] is useful when scrollables are nested and the
    /// target [`Scrollable`] is not the closest instance.
    ///
    /// This finds the nearest _ancestor_ [`Scrollable`] of the `context`. This
    /// means that if the `context` is that of a [`Scrollable`], it will _not_ find
    /// _that_ [`Scrollable`].
    ///
    /// See also:
    ///
    /// * [`Scrollable::of`], which is similar to this method, but panics
    ///   if no [`Scrollable`] ancestor is found.
    pub fn maybe_of(
        app: &mut App,
        context: BuildContext,
        axis: Option<Axis>,
    ) -> Option<Handle<ScrollableState>> {
        // This is the context that will need to establish the dependency.
        let original_context = context;
        let mut context = context;
        let mut element =
            context.get_element_for_inherited_widget_of_exact_type::<ScrollableScope>(app);
        while let Some(current) = element {
            let scrollable = ScrollableScope::of_element(app, current).scrollable;
            if axis
                .is_none_or(|axis| axis_direction_to_axis(scrollable.axis_direction(app)) == axis)
            {
                // Establish the dependency on the correct context.
                original_context.depend_on_inherited_element(app, current, None);
                return Some(scrollable);
            }
            context = scrollable.context(app);
            element =
                context.get_element_for_inherited_widget_of_exact_type::<ScrollableScope>(app);
        }
        None
    }

    /// The state from the closest instance of this class that encloses the given
    /// context.
    ///
    /// Calling this method will create a dependency on the [`ScrollableState`]
    /// that is returned.
    ///
    /// # Panics
    ///
    /// If no [`Scrollable`] ancestor is found.
    ///
    /// See also:
    ///
    /// * [`Scrollable::maybe_of`], which is similar to this method, but returns `None`
    ///   if no [`Scrollable`] ancestor is found.
    pub fn of(app: &mut App, context: BuildContext, axis: Option<Axis>) -> Handle<ScrollableState> {
        Scrollable::maybe_of(app, context, axis).expect(
            "Scrollable.of() was called with a context that does not contain a Scrollable \
             widget.\n\
             No Scrollable widget ancestor could be found starting from the context that was \
             passed to Scrollable.of(). This can happen because you are using a widget that \
             looks for a Scrollable ancestor, but no such ancestor exists. When specifying an \
             axis, this method will only look for a Scrollable that matches the given Axis.",
        )
    }

    /// Provides a heuristic to determine if expensive frame-bound tasks should be
    /// deferred for the `context` at a specific point in time.
    ///
    /// Calling this method does _not_ create a dependency on any other widget.
    /// This also means that the value returned is only good for the point in time
    /// when it is called, and callers will not get updated if the value changes.
    ///
    /// The heuristic used is determined by the [`physics`](Self::physics) of this
    /// [`Scrollable`] via [`ScrollPhysics::recommend_deferred_loading`](crate::ScrollPhysics::recommend_deferred_loading).
    ///
    /// If there is no [`Scrollable`] in the widget tree above the `context`, this
    /// method returns false.
    pub fn recommend_deferred_loading_for_context(
        app: &mut App,
        context: BuildContext,
        axis: Option<Axis>,
    ) -> bool {
        let mut context = context;
        loop {
            let Some(widget) = context.get_inherited_widget_of_exact_type::<ScrollableScope>(app)
            else {
                return false;
            };
            let (scrollable, position) = (widget.scrollable, widget.position.handle());
            if axis
                .is_none_or(|axis| axis_direction_to_axis(scrollable.axis_direction(app)) == axis)
            {
                return position.recommend_deferred_loading(app, context);
            }
            context = scrollable.context(app);
        }
    }

    /// Scrolls all scrollables that enclose the given context so as to make the
    /// given context visible.
    ///
    /// The returned future completes once every enclosing scrollable's animation has ended.
    pub fn ensure_visible(
        app: &mut App,
        context: BuildContext,
        alignment: f64,
        duration: Duration,
        curve: Rc<dyn Curve>,
        alignment_policy: ScrollPositionAlignmentPolicy,
    ) -> CompleterFuture<()> {
        let mut futures: Vec<CompleterFuture<()>> = Vec::new();

        // The `target_render_object` is used to record the first target render object.
        // If there are multiple scrollable widgets nested, it is made to be as visible as
        // possible to improve the user experience. If it is already visible, then let the
        // outer render object be as visible as possible.
        let mut target_render_object: Option<AnyRenderObject> = None;
        let mut context = context;
        let mut scrollable = Scrollable::maybe_of(app, context, None);
        while let Some(current) = scrollable {
            let (new_futures, current) = current.perform_ensure_visible(
                app,
                context.find_render_object(app).expect("a render object"),
                alignment,
                duration,
                curve.clone(),
                alignment_policy,
                target_render_object,
            );
            futures.extend(new_futures);

            if target_render_object.is_none() {
                target_render_object = context.find_render_object(app);
            }
            context = current.context(app);
            scrollable = Scrollable::maybe_of(app, context, None);
        }

        if futures.is_empty() || duration.is_zero() {
            return CompleterFuture::ready(());
        }
        if futures.len() == 1 {
            return futures.pop().expect("the single future");
        }
        CompleterFuture::spawn(app, async move {
            wait_all(futures).await;
        })
    }
}

impl StatefulWidget for Scrollable {
    type State = ScrollableState;

    fn key(&self) -> Option<&KeyRef> {
        self.key.as_ref()
    }

    fn create_state(&self) -> ScrollableState {
        ScrollableState {
            state: StateData::new(),
            ticker_provider: TickerProviderStateMixinData::new(),
            restoration: RestorationMixinData::new(),
            position: None,
            physics: None,
            persisted_scroll_offset: None,
            configuration: None,
            fallback_scroll_controller: None,
            media_query_gesture_settings: None,
            device_pixel_ratio: 1.0,
            gesture_detector_key: GlobalKey::new(),
            ignore_pointer_key: GlobalKey::new(),
            gesture_recognizers: Vec::new(),
            should_ignore_pointer: false,
            last_can_drag: None,
            last_axis_direction: None,
            drag: None,
            hold: None,
            scroll_context: None,
        }
    }
}

impl Debug for Scrollable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Scrollable")
            .field("axisDirection", &self.axis_direction)
            .field("physics", &self.physics)
            .field("restorationId", &self.restoration_id)
            .finish()
    }
}

/// Enables [`Scrollable::of`] to work as if [`ScrollableState`] was an inherited widget.
///
/// [`ScrollableState::build`] always rebuilds its scope; Dart's `_ScrollableScope`.
#[derive(Debug)]
struct ScrollableScope {
    scrollable: Handle<ScrollableState>,
    position: ScrollPositionRef,
    child: WidgetRef,
}

impl ScrollableScope {
    /// The scope an inherited element holds.
    fn of_element(app: &App, element: crate::framework::AnyElement) -> &ScrollableScope {
        crate::framework::downcast_widget::<ScrollableScope>(&**element.widget(app))
            .expect("a _ScrollableScope element holds a _ScrollableScope")
    }
}

impl InheritedWidget for ScrollableScope {
    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old: &ScrollableScope) -> bool {
        self.position != old.position
    }
}

/// State object for a [`Scrollable`] widget.
///
/// To manipulate a [`Scrollable`] widget's scroll position, use the object
/// obtained from the [`position`](Self::position) property.
///
/// To be informed of when a [`Scrollable`] widget is scrolling, use a
/// `NotificationListener` to listen for [`crate::ScrollNotification`] notifications.
pub struct ScrollableState {
    state: StateData<Scrollable>,
    ticker_provider: TickerProviderStateMixinData,
    restoration: RestorationMixinData,
    position: Option<ScrollPositionRef>,
    physics: Option<ScrollPhysicsRef>,
    persisted_scroll_offset: Option<Ref<RestorableScrollOffset>>,
    configuration: Option<ScrollBehaviorRef>,
    fallback_scroll_controller: Option<Ref<ScrollController>>,
    media_query_gesture_settings: Option<DeviceGestureSettings>,
    device_pixel_ratio: f64,
    gesture_detector_key: GlobalKey,
    ignore_pointer_key: GlobalKey,
    // This field is set during layout, and then reused until the next time it is set.
    gesture_recognizers: GestureRecognizerFactories,
    should_ignore_pointer: bool,
    last_can_drag: Option<bool>,
    last_axis_direction: Option<Axis>,
    drag: Option<Rc<dyn Drag>>,
    hold: Option<Rc<dyn ScrollHoldController>>,
    /// This state as the `ScrollContext` its position holds, minted once in `init_state`: a
    /// position compares contexts by identity, and Dart passes `this`.
    scroll_context: Option<Rc<dyn ScrollContext>>,
}

impl ScrollableState {
    /// The manager for this [`Scrollable`] widget's viewport position.
    ///
    /// To control what kind of [`ScrollPosition`](crate::ScrollPosition) is created for a [`Scrollable`],
    /// provide it with a custom `ScrollController` that creates the appropriate
    /// [`ScrollPosition`](crate::ScrollPosition) in its
    /// [`create_scroll_position`](ScrollControllerLeaf::create_scroll_position) method.
    pub fn position(self: Handle<Self>, app: &App) -> AnyScrollPosition {
        app.get(self)
            .position
            .handle()
            .expect("the position is created in didChangeDependencies")
    }

    /// The resolved [`ScrollPhysics`](crate::ScrollPhysics) of the [`ScrollableState`].
    pub fn resolved_physics(self: Handle<Self>, app: &App) -> Option<ScrollPhysicsRef> {
        app.get(self).physics.clone()
    }

    /// An [`Offset`] that represents the absolute distance from the origin, or 0,
    /// of the [`ScrollPosition`](crate::ScrollPosition) expressed in the associated [`Axis`].
    ///
    /// Used by an auto scroller to progress the position forward when a drag gesture reaches
    /// the edge of the viewport.
    pub fn delta_to_scroll_origin(self: Handle<Self>, app: &App) -> Offset {
        let pixels = self.position(app).pixels(app);
        match self.axis_direction(app) {
            AxisDirection::Up => Offset::new(0.0, -pixels),
            AxisDirection::Down => Offset::new(0.0, pixels),
            AxisDirection::Left => Offset::new(-pixels, 0.0),
            AxisDirection::Right => Offset::new(pixels, 0.0),
        }
    }

    /// The controller this scrollable's position is attached to; Dart's
    /// `_effectiveScrollController`.
    fn effective_scroll_controller(self: Handle<Self>, app: &App) -> ScrollControllerRef {
        self.widget(app).controller.clone().unwrap_or_else(|| {
            app.get(self)
                .fallback_scroll_controller
                .as_ref()
                .expect("a scrollable without a controller creates a fallback")
                .erase()
        })
    }

    /// The [`position`](Self::position) as a reference, for a caller that keeps it: a field
    /// Dart types as the `ScrollPosition` it reads from a `ScrollableState`.
    pub fn kept_position(self: Handle<Self>, app: &App) -> ScrollPositionRef {
        app.get(self)
            .position
            .clone()
            .expect("the position is created in didChangeDependencies")
    }

    fn persisted_scroll_offset(self: Handle<Self>, app: &App) -> Handle<RestorableScrollOffset> {
        app.get(self)
            .persisted_scroll_offset
            .handle()
            .expect("the property is created in initState")
    }

    fn configuration(self: Handle<Self>, app: &App) -> ScrollBehaviorRef {
        app.get(self)
            .configuration
            .clone()
            .expect("the configuration is read in didChangeDependencies")
    }

    // Only call this from places that will definitely trigger a rebuild.
    fn scroll_context(self: Handle<Self>, app: &App) -> Rc<dyn ScrollContext> {
        Rc::clone(
            app.get(self)
                .scroll_context
                .as_ref()
                .expect("init_state has run"),
        )
    }

    fn update_position(self: Handle<Self>, app: &mut App) {
        let context = self.context(app);
        let widget_behavior = self.widget(app).scroll_behavior.clone();
        let configuration = match widget_behavior.clone() {
            Some(behavior) => behavior,
            None => ScrollConfiguration::of(app, context),
        };
        app.get_mut(self).configuration = Some(configuration.clone());
        let physics_from_widget =
            self.widget(app).physics.clone().or_else(|| {
                widget_behavior.map(|behavior| behavior.get_scroll_physics(app, context))
            });
        let mut physics = configuration.get_scroll_physics(app, context);
        physics = physics_from_widget.map_or(physics.clone(), |from_widget| {
            from_widget.apply_to(Some(physics))
        });
        app.get_mut(self).physics = Some(physics.clone());

        let old_position = app.get_mut(self).position.take();
        if let Some(old_position) = old_position.clone() {
            self.effective_scroll_controller(app)
                .detach(app, old_position.handle());
            // It's important that we not dispose the old position until after the viewport has
            // had a chance to unregister its listeners from the old position. So, schedule a
            // microtask to do it.
            app.schedule_microtask(Listener::new(move |app| old_position.dispose(app)));
        }

        let scroll_context = self.scroll_context(app);
        let position = self
            .effective_scroll_controller(app)
            .create_scroll_position(app, physics, scroll_context, old_position.handle());
        app.get_mut(self).position = Some(position.clone());
        self.effective_scroll_controller(app).attach(app, position);
    }

    fn should_update_position(self: Handle<Self>, app: &mut App, old_widget: &Scrollable) -> bool {
        let scroll_behavior = self.widget(app).scroll_behavior.clone();
        if scroll_behavior.is_none() != old_widget.scroll_behavior.is_none() {
            return true;
        }
        if let (Some(behavior), Some(old_behavior)) =
            (&scroll_behavior, &old_widget.scroll_behavior)
            && behavior.should_notify(&**old_behavior)
        {
            return true;
        }
        let context = self.context(app);
        let mut new_physics = self.widget(app).physics.clone().or_else(|| {
            scroll_behavior
                .as_ref()
                .map(|behavior| behavior.get_scroll_physics(app, context))
        });
        let mut old_physics = old_widget.physics.clone().or_else(|| {
            old_widget
                .scroll_behavior
                .as_ref()
                .map(|behavior| behavior.get_scroll_physics(app, context))
        });
        loop {
            let new_type = new_physics
                .as_ref()
                .map(|physics| physics.as_any().type_id());
            let old_type = old_physics
                .as_ref()
                .map(|physics| physics.as_any().type_id());
            if new_type != old_type {
                return true;
            }
            new_physics = new_physics.and_then(|physics| physics.parent().cloned());
            old_physics = old_physics.and_then(|physics| physics.parent().cloned());
            if new_physics.is_none() && old_physics.is_none() {
                break;
            }
        }

        self.widget(app)
            .controller
            .handle()
            .map(|controller| controller.type_id())
            != old_widget
                .controller
                .handle()
                .map(|controller| controller.type_id())
    }

    // TOUCH HANDLERS

    fn handle_drag_down(self: Handle<Self>, app: &mut App, _details: DragDownDetails) {
        debug_assert!(app.get(self).drag.is_none());
        debug_assert!(app.get(self).hold.is_none());
        let hold = self
            .position(app)
            .hold(app, Listener::handle_method(self, Self::dispose_hold));
        app.get_mut(self).hold = Some(hold);
    }

    fn handle_drag_start(self: Handle<Self>, app: &mut App, details: DragStartDetails) {
        // It's possible for the hold to become `None` between `handle_drag_down` and
        // `handle_drag_start`, for example if some user code calls jumpTo or otherwise
        // triggers a new activity to begin.
        debug_assert!(app.get(self).drag.is_none());
        let drag = self.position(app).drag(
            app,
            details,
            Listener::handle_method(self, Self::dispose_drag),
        );
        app.get_mut(self).drag = Some(drag);
        // The hold might be non-`None` if the scroll position is currently animating.
        if app.get(self).hold.is_some() {
            self.dispose_hold(app);
        }
    }

    fn handle_drag_update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
        // The drag might be `None` if the drag activity ended and called `dispose_drag`.
        debug_assert!(app.get(self).hold.is_none() || app.get(self).drag.is_none());
        if let Some(drag) = app.get(self).drag.clone() {
            drag.update(app, details);
        }
    }

    fn handle_drag_end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
        // The drag might be `None` if the drag activity ended and called `dispose_drag`.
        debug_assert!(app.get(self).hold.is_none() || app.get(self).drag.is_none());
        if let Some(drag) = app.get(self).drag.clone() {
            drag.end(app, details);
        }
        debug_assert!(app.get(self).drag.is_none());
    }

    fn handle_drag_cancel(self: Handle<Self>, app: &mut App) {
        if self
            .gesture_detector_key(app)
            .current_context(app)
            .is_none()
        {
            // The cancel was caused by the gesture detector getting disposed, which means we
            // will get disposed momentarily as well and shouldn't do any work.
            return;
        }
        // The hold might be `None` if the drag started.
        // The drag might be `None` if the drag activity ended and called `dispose_drag`.
        debug_assert!(app.get(self).hold.is_none() || app.get(self).drag.is_none());
        if let Some(hold) = app.get(self).hold.clone() {
            hold.cancel(app);
        }
        if let Some(drag) = app.get(self).drag.clone() {
            drag.cancel(app);
        }
        debug_assert!(app.get(self).hold.is_none());
        debug_assert!(app.get(self).drag.is_none());
    }

    fn dispose_hold(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).hold = None;
    }

    fn dispose_drag(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).drag = None;
    }

    fn gesture_detector_key(self: Handle<Self>, app: &App) -> GlobalKey {
        app.get(self).gesture_detector_key.clone()
    }

    // SCROLL WHEEL

    /// Returns the offset that should result from applying `delta` to the current position,
    /// taking min/max scroll extent into account.
    fn target_scroll_offset_for_pointer_scroll(self: Handle<Self>, app: &App, delta: f64) -> f64 {
        let position = self.position(app);
        (position.pixels(app) + delta)
            .max(position.min_scroll_extent(app))
            .min(position.max_scroll_extent(app))
    }

    /// Returns the delta that should result from applying `event` with axis,
    /// direction, and any modifiers specified by the scroll behavior taken into account.
    fn pointer_signal_event_delta(self: Handle<Self>, app: &mut App, event: &PointerEvent) -> f64 {
        let PointerEvent::Scroll(scroll) = event else {
            unreachable!("a pointer signal delta is only read for a scroll event");
        };
        let pressed = HardwareKeyboard::instance(app).logical_keys_pressed(app);
        let modifiers = self.configuration(app).pointer_axis_modifiers();
        let flip_axes = pressed.iter().any(|key| modifiers.contains(key))
            // Axes are only flipped for physical mouse wheel input.
            // On some platforms, like web, trackpad input is handled through pointer
            // signals, but should not be included in this axis modifying behavior.
            // This is because on a trackpad, all directional axes are available to
            // the user, while mouse scroll wheels typically are restricted to one axis.
            && event.kind() == waft_embedder::PointerDeviceKind::Mouse;

        let widget_axis = self.widget(app).axis();
        let axis = if flip_axes {
            flip_axis(widget_axis)
        } else {
            widget_axis
        };
        let delta = match axis {
            Axis::Horizontal => scroll.scroll_delta.dx(),
            Axis::Vertical => scroll.scroll_delta.dy(),
        };

        if axis_direction_is_reversed(self.widget(app).axis_direction) {
            -delta
        } else {
            delta
        }
    }

    fn received_pointer_signal(self: Handle<Self>, app: &mut App, event: &PointerEvent) {
        match event {
            PointerEvent::Scroll(_) if app.get(self).position.is_some() => {
                if let Some(physics) = self.resolved_physics(app) {
                    let metrics = self.position(app).copy_with(app);
                    if !physics.should_accept_user_offset(&*metrics) {
                        return;
                    }
                }
                let delta = self.pointer_signal_event_delta(app, event);
                let target_scroll_offset = self.target_scroll_offset_for_pointer_scroll(app, delta);
                // Only express interest in the event if it would actually result in a scroll.
                if delta != 0.0 && target_scroll_offset != self.position(app).pixels(app) {
                    let resolver = GestureBinding::instance(app).pointer_signal_resolver(app);
                    resolver.register(
                        app,
                        event,
                        Rc::new(move |app, event| self.handle_pointer_scroll(app, event)),
                    );
                }
            }
            PointerEvent::ScrollInertiaCancel(_) => {
                // Don't use the pointer signal resolver, all hit-tested scrollables should stop.
                self.position(app).pointer_scroll(app, 0.0);
            }
            _ => {}
        }
    }

    fn handle_pointer_scroll(self: Handle<Self>, app: &mut App, event: &PointerEvent) {
        debug_assert!(matches!(event, PointerEvent::Scroll(_)));
        let delta = self.pointer_signal_event_delta(app, event);
        let target_scroll_offset = self.target_scroll_offset_for_pointer_scroll(app, delta);
        if delta != 0.0 && target_scroll_offset != self.position(app).pixels(app) {
            self.position(app).pointer_scroll(app, delta);
        }
    }

    fn build_chrome(
        self: Handle<Self>,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
    ) -> WidgetRef {
        let (axis_direction, clip_behavior) = {
            let widget = self.widget(app);
            (widget.axis_direction, widget.clip_behavior)
        };
        let details = ScrollableDetails::new(axis_direction)
            .controller(self.effective_scroll_controller(app))
            .decoration_clip_behavior(clip_behavior);

        let configuration = self.configuration(app);
        let decorated = configuration.build_overscroll_indicator(app, context, child, &details);
        configuration.build_scrollbar(app, context, decorated, &details)
    }

    /// Runs `ensure_visible` for the scroll position, so its context can be used to
    /// check for other ancestor scrollables in executing
    /// [`Scrollable::ensure_visible`]; Dart's `_performEnsureVisible`.
    #[allow(clippy::too_many_arguments)]
    fn perform_ensure_visible(
        self: Handle<Self>,
        app: &mut App,
        object: AnyRenderObject,
        alignment: f64,
        duration: Duration,
        curve: Rc<dyn Curve>,
        alignment_policy: ScrollPositionAlignmentPolicy,
        target_render_object: Option<AnyRenderObject>,
    ) -> EnsureVisibleResults {
        let ensure_visible_future = self.position(app).ensure_visible(
            app,
            object,
            alignment,
            duration,
            curve,
            alignment_policy,
            target_render_object,
        );
        (vec![ensure_visible_future], self)
    }
}

impl TickerProviderObject for ScrollableState {
    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
        TickerProviderStateMixin::create_ticker(self, app, on_tick)
    }
}

impl TickerProviderStateMixin for ScrollableState {
    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
        &app.get(self).ticker_provider
    }

    fn ticker_provider_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut TickerProviderStateMixinData {
        &mut app.get_mut(self).ticker_provider
    }
}

impl RestorationMixin for ScrollableState {
    crate::restoration_mixin_accessors!();

    fn restoration_id(self: Handle<Self>, app: &App) -> Option<&str> {
        self.widget(app).restoration_id.as_deref()
    }

    fn restore_state(
        self: Handle<Self>,
        app: &mut App,
        _old_bucket: Option<Handle<RestorationBucket>>,
        initial_restore: bool,
    ) {
        let property = self.persisted_scroll_offset(app);
        self.register_for_restoration(app, property.as_property(), "offset");
        debug_assert!(app.get(self).position.is_some());
        if let Some(offset) = *RestorableValue::value(property, app) {
            self.position(app)
                .restore_offset(app, offset, initial_restore);
        }
    }
}

impl ScrollContext for Handle<ScrollableState> {
    fn type_name(&self) -> &'static str {
        "ScrollableState"
    }

    fn handle_id(&self) -> HandleId {
        self.id()
    }

    fn vsync(&self) -> Rc<dyn TickerProvider> {
        Rc::new(*self)
    }

    fn notification_context(&self, app: &mut App) -> Option<BuildContext> {
        let this = *self;
        app.get(this)
            .gesture_detector_key
            .clone()
            .current_context(app)
    }

    fn storage_context(&self, app: &App) -> BuildContext {
        let this = *self;
        this.context(app)
    }

    fn axis_direction(&self, app: &App) -> AxisDirection {
        let this = *self;
        this.widget(app).axis_direction
    }

    fn device_pixel_ratio(&self, app: &App) -> f64 {
        let this = *self;
        app.get(this).device_pixel_ratio
    }

    fn set_ignore_pointer(&self, app: &mut App, value: bool) {
        let this = *self;
        if app.get(this).should_ignore_pointer == value {
            return;
        }
        app.get_mut(this).should_ignore_pointer = value;
        let ignore_pointer_key = app.get(this).ignore_pointer_key.clone();
        if let Some(context) = ignore_pointer_key.current_context(app) {
            let render_box = context
                .find_render_object(app)
                .expect("a mounted IgnorePointer has a render object")
                .downcast::<RenderIgnorePointer>(app)
                .expect("the IgnorePointer's render object");
            render_box.set_ignoring(app, value);
        }
    }

    fn set_can_drag(&self, app: &mut App, value: bool) {
        let this = *self;
        let widget_axis = this.widget(app).axis();
        if Some(value) == app.get(this).last_can_drag
            && (!value || Some(widget_axis) == app.get(this).last_axis_direction)
        {
            return;
        }
        if value {
            let configuration = this.configuration(app);
            let context = this.context(app);
            let drag_devices = configuration.drag_devices();
            let velocity_tracker_builder = configuration.velocity_tracker_builder(app, context);
            let multitouch_drag_strategy = configuration.get_multitouch_drag_strategy(app, context);
            let gesture_settings = app.get(this).media_query_gesture_settings;
            let drag_start_behavior = this.widget(app).drag_start_behavior;
            let physics = this.resolved_physics(app);
            let (min_fling_distance, min_fling_velocity, max_fling_velocity) = (
                physics.as_ref().map(|physics| physics.min_fling_distance()),
                physics.as_ref().map(|physics| physics.min_fling_velocity()),
                physics.as_ref().map(|physics| physics.max_fling_velocity()),
            );
            let constructed_devices = drag_devices.clone();
            macro_rules! drag_factory {
                ($recognizer:ty) => {{
                    let devices = drag_devices.clone();
                    let velocity_tracker_builder = velocity_tracker_builder.clone();
                    GestureRecognizerFactoryWithHandlers::<$recognizer>::new(
                        move |app| {
                            let instance = <$recognizer>::new(app);
                            instance.set_supported_devices(app, Some(constructed_devices.clone()));
                            instance
                        },
                        move |app, instance| {
                            instance.set_on_down(
                                app,
                                Some(Rc::new(move |app: &mut App, details| {
                                    this.handle_drag_down(app, details);
                                })),
                            );
                            instance.set_on_start(
                                app,
                                Some(Rc::new(move |app: &mut App, details| {
                                    this.handle_drag_start(app, details);
                                })),
                            );
                            instance.set_on_update(
                                app,
                                Some(Rc::new(move |app: &mut App, details| {
                                    this.handle_drag_update(app, details);
                                })),
                            );
                            instance.set_on_end(
                                app,
                                Some(Rc::new(move |app: &mut App, details| {
                                    this.handle_drag_end(app, details);
                                })),
                            );
                            instance.set_on_cancel(
                                app,
                                Some(Listener::handle_method(
                                    this,
                                    ScrollableState::handle_drag_cancel,
                                )),
                            );
                            instance.set_min_fling_distance(app, min_fling_distance);
                            instance.set_min_fling_velocity(app, min_fling_velocity);
                            instance.set_max_fling_velocity(app, max_fling_velocity);
                            instance.set_velocity_tracker_builder(
                                app,
                                velocity_tracker_builder.clone(),
                            );
                            instance.set_drag_start_behavior(app, drag_start_behavior);
                            instance.set_multitouch_drag_strategy(app, multitouch_drag_strategy);
                            instance.set_gesture_settings(app, gesture_settings);
                            instance.set_supported_devices(app, Some(devices.clone()));
                        },
                    )
                    .into_factory()
                }};
            }
            let recognizers: GestureRecognizerFactories = match widget_axis {
                Axis::Vertical => vec![(
                    TypeId::of::<VerticalDragGestureRecognizer>(),
                    drag_factory!(VerticalDragGestureRecognizer),
                )],
                Axis::Horizontal => vec![(
                    TypeId::of::<HorizontalDragGestureRecognizer>(),
                    drag_factory!(HorizontalDragGestureRecognizer),
                )],
            };
            app.get_mut(this).gesture_recognizers = recognizers;
        } else {
            app.get_mut(this).gesture_recognizers = Vec::new();
            // Cancel the active hold/drag (if any) because the gesture recognizers
            // will soon be disposed by our RawGestureDetector, and we won't be
            // receiving pointer up events to cancel the hold/drag.
            this.handle_drag_cancel(app);
        }
        app.get_mut(this).last_can_drag = Some(value);
        app.get_mut(this).last_axis_direction = Some(widget_axis);
        let gesture_detector_key = app.get(this).gesture_detector_key.clone();
        if let Some(detector) = gesture_detector_key.current_state::<RawGestureDetectorState>(app) {
            let recognizers = app.get(this).gesture_recognizers.clone();
            detector.replace_gesture_recognizers(app, recognizers);
        }
    }

    fn save_offset(&self, app: &mut App, offset: f64) {
        let this = *self;
        let property = this.persisted_scroll_offset(app);
        property.set_value(app, Some(offset));
        // `save_offset` is called after a scrolling ends and it is usually not
        // followed by a frame. Therefore, manually flush restoration data.
        RestorationManager::instance(app).flush_data(app);
    }
}

impl State for ScrollableState {
    type Widget = Scrollable;
    crate::state_accessors!();

    fn init_state(self: Handle<Self>, app: &mut App) {
        app.get_mut(self).scroll_context = Some(Rc::new(self));
        let property = RestorableScrollOffset::new(app);
        app.get_mut(self).persisted_scroll_offset = Some(property);
        if self.widget(app).controller.is_none() {
            let fallback = ScrollController::default(app);
            app.get_mut(self).fallback_scroll_controller = Some(fallback);
        }
    }

    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
        let context = self.context(app);
        app.get_mut(self).media_query_gesture_settings =
            MediaQuery::maybe_gesture_settings_of(app, context);
        let device_pixel_ratio = MediaQuery::maybe_device_pixel_ratio_of(app, context)
            .unwrap_or_else(|| View::of(app, context).metrics().device_pixel_ratio);
        app.get_mut(self).device_pixel_ratio = device_pixel_ratio;
        self.update_position(app);
        self.did_change_dependencies_restoration(app);
    }

    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &Scrollable) {
        self.did_update_restoration_id(app);

        let controller = self.widget(app).controller.handle();
        if controller != old_widget.controller.handle() {
            let position = self.position(app);
            match old_widget.controller.handle() {
                None => {
                    // The old controller was `None`, meaning the fallback cannot be `None`.
                    // Dispose of the fallback.
                    let fallback = app
                        .get(self)
                        .fallback_scroll_controller
                        .handle()
                        .expect("a scrollable without a controller has a fallback");
                    debug_assert!(controller.is_some());
                    fallback.detach(app, position);
                    ScrollControllerLeaf::dispose(fallback, app);
                    app.get_mut(self).fallback_scroll_controller = None;
                }
                Some(old_controller) => {
                    // The old controller was not `None`, detach.
                    old_controller.detach(app, position);
                    if controller.is_none() {
                        // If the new controller is `None`, we need to set up the fallback.
                        let fallback = ScrollController::default(app);
                        app.get_mut(self).fallback_scroll_controller = Some(fallback);
                    }
                }
            }
            // Attach the updated effective scroll controller.
            let position = self.kept_position(app);
            self.effective_scroll_controller(app).attach(app, position);
        }

        if self.should_update_position(app, old_widget) {
            self.update_position(app);
        }
    }

    fn dispose(self: Handle<Self>, app: &mut App) {
        let position = self.position(app);
        match self.widget(app).controller.handle() {
            Some(controller) => controller.detach(app, position),
            None => {
                if let Some(fallback) = app.get(self).fallback_scroll_controller.handle() {
                    fallback.detach(app, position);
                    ScrollControllerLeaf::dispose(fallback, app);
                }
            }
        }

        position.dispose(app);
        RestorableProperty::dispose(self.persisted_scroll_offset(app), app);
        self.dispose_restoration(app);
        TickerProviderStateMixin::dispose(self, app);
    }

    fn activate(self: Handle<Self>, app: &mut App) {
        TickerProviderStateMixin::activate(self, app);
    }

    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
        debug_assert!(app.get(self).position.is_some());
        // The scope must be placed above the build context returned by
        // `notification_context` so that we can get this state by doing the following:
        //
        //     Scrollable::of(app, notification.context())
        //
        // Since `notification_context` points to the gesture detector's context, the scope
        // must be placed above the widget using it: `RawGestureDetector`.
        let position = self.kept_position(app);
        let viewport_builder = self.widget(app).viewport_builder.clone();
        let viewport = viewport_builder(app, context, position.erase());
        let hit_test_behavior = self.widget(app).hit_test_behavior;
        let state = app.get(self);
        let result = ScrollableScope {
            scrollable: self,
            position,
            child: PointerListener::new()
                .on_pointer_signal(Rc::new(move |app: &mut App, event| {
                    self.received_pointer_signal(app, &event);
                }))
                .child(
                    RawGestureDetector::new()
                        .key(state.gesture_detector_key.clone().into())
                        .gestures(state.gesture_recognizers.clone())
                        .behavior(hit_test_behavior)
                        .child(
                            IgnorePointer::new()
                                .key(state.ignore_pointer_key.clone().into())
                                .ignoring(state.should_ignore_pointer)
                                .child(viewport),
                        ),
                )
                .into_widget(),
        }
        .into_widget();

        self.build_chrome(app, context, result)
    }
}

impl Debug for ScrollableState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ScrollableState")
            .field("position", &self.position)
            .field("effective physics", &self.physics)
            .finish()
    }
}

/// Dart's `_RestorableScrollOffset`: the scroll offset a [`ScrollableState`] persists.
pub struct RestorableScrollOffset {
    change_notifier: waft_foundation::ChangeNotifierData,
    property: RestorablePropertyData,
    value: RestorableValueData<Option<f64>>,
}

impl RestorableScrollOffset {
    /// Creates a property whose default value is "no stored offset".
    pub fn new(app: &mut App) -> Ref<RestorableScrollOffset> {
        app.create(RestorableScrollOffset {
            change_notifier: waft_foundation::ChangeNotifierData::new(),
            property: RestorablePropertyData::new(),
            value: RestorableValueData::new(),
        })
    }
}

impl waft_foundation::ChangeNotifier for RestorableScrollOffset {
    fn change_notifier_data(&self) -> &waft_foundation::ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut waft_foundation::ChangeNotifierData {
        &mut self.change_notifier
    }
}

impl RestorableProperty for RestorableScrollOffset {
    type Value = Option<f64>;
    crate::restorable_property_accessors!();

    fn create_default_value(self: Handle<Self>, _app: &mut App) -> Option<f64> {
        None
    }

    fn from_primitives(self: Handle<Self>, _app: &mut App, data: &RestorationData) -> Option<f64> {
        Some(
            data.as_double()
                .expect("a stored scroll offset is a double"),
        )
    }

    fn init_with_value(self: Handle<Self>, app: &mut App, value: Option<f64>) {
        RestorableValue::init_with_value(self, app, value);
    }

    fn to_primitives(self: Handle<Self>, app: &App) -> RestorationData {
        match RestorableValue::value(self, app) {
            Some(offset) => RestorationData::Double(*offset),
            None => RestorationData::Null,
        }
    }

    fn enabled(self: Handle<Self>, app: &App) -> bool {
        RestorableValue::value(self, app).is_some()
    }
}

impl RestorableValue for RestorableScrollOffset {
    crate::restorable_value_accessors!();

    fn did_update_value(self: Handle<Self>, app: &mut App, _old_value: Option<Option<f64>>) {
        self.notify_listeners(app);
    }
}

#[cfg(test)]
mod tests {
    use std::cell::{Cell, RefCell};
    use std::collections::HashSet;
    use waft_foundation::AppCell;

    use waft_embedder::{PointerDeviceKind, Restoration, TargetPlatform, TextDirection};
    use waft_services::{RestorationMap, RestorationUpdate};
    use waft_test::TestPlatform;

    use super::*;
    use crate::framework::Element;
    use crate::test_harness::Harness;
    use crate::test_harness::pump_every_view;
    use crate::testing::{
        TargetPlatformVariant, TestPointer, WidgetTester, find, test_widgets, test_widgets_variant,
    };
    use crate::widgets::basic::{Builder, Directionality, SizedBox, SliverToBoxAdapter};
    use crate::widgets::media_query::{MediaQuery, MediaQueryData};
    use crate::widgets::restoration::RootRestorationScope;
    use crate::widgets::scroll_configuration::ScrollBehavior;
    use crate::widgets::scroll_controller::ScrollControllerLeaf;
    use crate::widgets::scroll_view::CustomScrollView;
    use waft_rendering::{RenderBox, RenderSliver};

    /// A host that answers `Restoration::get` with what it was handed and records every
    /// `Restoration::put`.
    #[derive(Default)]
    struct RecordingRestoration {
        stored: RefCell<Option<RestorationUpdate>>,
        puts: RefCell<Vec<RestorationMap>>,
    }

    impl Restoration for RecordingRestoration {
        fn get(&self) -> Option<RestorationUpdate> {
            self.stored.borrow().clone()
        }

        fn put(&self, data: RestorationMap) {
            self.puts.borrow_mut().push(data);
        }
    }

    fn app_restoring(data: Option<RestorationMap>) -> (Rc<AppCell>, Rc<RecordingRestoration>) {
        let restoration = Rc::new(RecordingRestoration::default());
        *restoration.stored.borrow_mut() = Some(RestorationUpdate {
            enabled: true,
            data,
        });
        let platform = TestPlatform::new().with_restoration(restoration.clone());
        (AppCell::with_platform(Rc::new(platform)), restoration)
    }

    fn map<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
        entries
            .into_iter()
            .map(|(key, value)| (RestorationData::from(key), value))
            .collect()
    }

    fn values<const N: usize>(entries: [(&str, RestorationData); N]) -> RestorationMap {
        map([("v", map(entries).into())])
    }

    fn child(restoration_id: &str, data: RestorationMap) -> RestorationMap {
        map([("c", map([(restoration_id, data.into())]).into())])
    }

    fn at<'a>(data: &'a RestorationMap, path: &[&str]) -> Option<&'a RestorationData> {
        let (last, parents) = path.split_last()?;
        let mut map = data;
        for key in parents {
            map = map.get(&RestorationData::from(*key))?.as_map()?;
        }
        map.get(&RestorationData::from(*last))
    }

    /// A viewport builder that records the offset it is handed and builds a leaf box.
    fn box_viewport() -> ViewportBuilder {
        Rc::new(|_app, _context, _offset| SizedBox::shrink().into_widget())
    }

    /// Mounts `scrollable` under a `MediaQuery` and hands back the state.
    fn mount_scrollable(
        app: &mut App,
        scrollable: Scrollable,
    ) -> (Harness, Handle<ScrollableState>) {
        let harness = Harness::mount(
            app,
            MediaQuery::new(MediaQueryData::new(), scrollable).into_widget(),
        );
        harness.pump(app);
        // MediaQuery, its inherited model scope, then the Scrollable's stateful element.
        let mut element = harness.root.as_element();
        let state = loop {
            element = element.children(app)[0];
            if let Some(state) = element.state_handle::<ScrollableState>(app) {
                break state;
            }
        };
        (harness, state)
    }

    /// A leaf widget whose render object is a `RenderViewport` over 800 logical pixels of
    /// content: what the `Viewport` widget builds, in miniature.
    #[derive(Debug)]
    struct TestViewport {
        offset: ViewportOffsetRef,
    }

    impl crate::framework::RenderObjectWidget for TestViewport {
        type RenderObject = waft_rendering::RenderViewport;

        fn create_render_object(
            &self,
            app: &mut App,
            _context: BuildContext,
        ) -> waft_rendering::AnyRenderObject {
            let content = waft_rendering::RenderConstrainedBox::new(
                app,
                waft_rendering::BoxConstraints::tight(waft_embedder::Size::new(300.0, 800.0)),
                None,
            );
            let sliver = waft_rendering::RenderSliverToBoxAdapter::new(
                app,
                Some(waft_rendering::RenderBox::as_box(content)),
            );
            waft_rendering::RenderViewport::new(
                app,
                AxisDirection::Right,
                self.offset.clone(),
                Some(vec![RenderSliver::as_sliver(sliver)]),
                None,
            )
            .as_object()
        }

        fn update_render_object(
            &self,
            app: &mut App,
            _context: BuildContext,
            render_object: waft_rendering::RenderHandle<waft_rendering::RenderViewport>,
        ) {
            waft_rendering::RenderViewportBase::set_offset(render_object, app, self.offset.clone());
        }
    }

    impl crate::framework::LeafRenderObjectWidget for TestViewport {}

    #[test]
    fn a_laid_out_scrollable_takes_its_dimensions_from_its_viewport() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let viewport: ViewportBuilder =
            Rc::new(|_app, _context, offset| TestViewport { offset }.into_widget());
        let (_harness, state) = mount_scrollable(&mut app, Scrollable::new(viewport));

        let position = state.position(&app);
        assert!(position.have_dimensions(&app));
        assert_eq!(
            position.viewport_dimension(&app),
            crate::test_harness::VIEW_HEIGHT
        );
        assert_eq!(
            position.max_scroll_extent(&app),
            800.0 - crate::test_harness::VIEW_HEIGHT
        );
        assert_eq!(position.min_scroll_extent(&app), 0.0);
        assert_eq!(position.pixels(&app), 0.0);
        // The physics accept a user offset, so the drag recognizer factory is in place.
        assert_eq!(app.get(state).gesture_recognizers.len(), 1);
    }

    #[test]
    fn a_scrollable_creates_a_position_on_its_effective_controller() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let controller = ScrollController::new(&mut app, 17.0, true, None, None, None);
        let (_harness, state) = mount_scrollable(
            &mut app,
            Scrollable::new(box_viewport()).controller(controller.erase()),
        );

        assert_eq!(state.position(&app).pixels(&app), 17.0);
        assert_eq!(controller.positions(&app), vec![state.position(&app)]);
        assert_eq!(state.axis_direction(&app), AxisDirection::Down);
        assert!(state.resolved_physics(&app).is_some());
        assert_eq!(state.delta_to_scroll_origin(&app), Offset::new(0.0, 17.0));
    }

    #[test]
    fn a_scrollable_without_a_controller_uses_a_fallback_one() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let (_harness, state) = mount_scrollable(&mut app, Scrollable::new(box_viewport()));

        assert_eq!(state.position(&app).pixels(&app), 0.0);
        assert!(app.get(state).fallback_scroll_controller.is_some());
    }

    #[test]
    fn of_finds_the_state_from_a_descendant_of_the_viewport() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let seen: Rc<Cell<Option<BuildContext>>> = Rc::new(Cell::new(None));
        let captured = seen.clone();
        let viewport: ViewportBuilder = Rc::new(move |_app, _context, _offset| {
            let captured = captured.clone();
            Builder::new(move |_app, context| {
                captured.set(Some(context));
                SizedBox::shrink().into_widget()
            })
            .into_widget()
        });
        let (_harness, state) = mount_scrollable(&mut app, Scrollable::new(viewport));

        let inner = seen.get().expect("the viewport built");
        assert_eq!(Scrollable::maybe_of(&mut app, inner, None), Some(state));
        assert_eq!(
            Scrollable::maybe_of(&mut app, inner, Some(Axis::Vertical)),
            Some(state)
        );
        assert_eq!(
            Scrollable::maybe_of(&mut app, inner, Some(Axis::Horizontal)),
            None
        );
        assert_eq!(Scrollable::of(&mut app, inner, None), state);
        // No scrollable in the horizontal axis encloses the context, so the walk ends there.
        assert!(!Scrollable::recommend_deferred_loading_for_context(
            &mut app,
            inner,
            Some(Axis::Horizontal)
        ));
    }

    #[test]
    fn a_scrollable_restores_its_offset_through_the_restoration_mixin() {
        let (cell, _restoration) = app_restoring(Some(child(
            "app",
            child(
                "scroll",
                values([("offset", RestorationData::Double(42.0))]),
            ),
        )));
        let mut app = cell.borrow_mut();
        let scrollable = Scrollable::new(box_viewport()).restoration_id("scroll");
        let harness = Harness::mount(
            &mut app,
            RootRestorationScope::new(
                Some("app".to_string()),
                MediaQuery::new(MediaQueryData::new(), scrollable).into_widget(),
            )
            .into_widget(),
        );
        harness.pump(&mut app);

        let mut element = harness.root.as_element();
        let state = loop {
            element = element.children(&app)[0];
            if let Some(state) = element.state_handle::<ScrollableState>(&app) {
                break state;
            }
        };
        assert_eq!(state.position(&app).pixels(&app), 42.0);
    }

    #[test]
    fn saving_an_offset_writes_it_into_the_restoration_data() {
        let (cell, restoration) = app_restoring(None);
        let mut app = cell.borrow_mut();
        let scrollable = Scrollable::new(box_viewport()).restoration_id("scroll");
        let harness = Harness::mount(
            &mut app,
            RootRestorationScope::new(
                Some("app".to_string()),
                MediaQuery::new(MediaQueryData::new(), scrollable).into_widget(),
            )
            .into_widget(),
        );
        harness.pump(&mut app);
        let mut element = harness.root.as_element();
        let state = loop {
            element = element.children(&app)[0];
            if let Some(state) = element.state_handle::<ScrollableState>(&app) {
                break state;
            }
        };

        ScrollContext::save_offset(&state, &mut app, 55.0);
        pump_every_view(&mut app, Duration::ZERO);

        let stored = restoration.puts.borrow();
        let last = stored.last().expect("the manager sent the data");
        assert_eq!(
            at(last, &["c", "app", "c", "scroll", "v", "offset"]),
            Some(&RestorationData::Double(55.0))
        );
    }

    #[test]
    fn the_scroll_context_reports_the_media_querys_device_pixel_ratio() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(
            &mut app,
            MediaQuery::new(
                MediaQueryData::new().device_pixel_ratio(3.0),
                Scrollable::new(box_viewport()),
            )
            .into_widget(),
        );
        harness.pump(&mut app);
        let mut element = harness.root.as_element();
        let state = loop {
            element = element.children(&app)[0];
            if let Some(state) = element.state_handle::<ScrollableState>(&app) {
                break state;
            }
        };

        assert_eq!(ScrollContext::device_pixel_ratio(&state, &app), 3.0);
        assert_eq!(state.position(&app).device_pixel_ratio(&app), 3.0);
    }

    // ---- scrollable_test.dart: holds, flings and carried momentum ----

    /// `scrollable_test.dart`'s `dragOffset`.
    const DRAG_OFFSET: f64 = 200.0;

    /// The center of the `Scrollable` [`pump_test`] mounts, which fills the 800 x 600 view:
    /// where Flutter's `tester.getCenter(find.byType(Scrollable))` puts a gesture.
    const SCROLLABLE_CENTER: Offset = Offset::new(400.0, 300.0);

    /// `scrollable_test.dart`'s `NoScrollbarBehavior`.
    #[derive(Debug)]
    struct NoScrollbarBehavior;

    impl ScrollBehavior for NoScrollbarBehavior {
        fn as_any(&self) -> &dyn std::any::Any {
            self
        }

        fn build_scrollbar(
            &self,
            _app: &mut App,
            _context: BuildContext,
            child: WidgetRef,
            _details: &ScrollableDetails,
        ) -> WidgetRef {
            child
        }
    }

    /// `tester.startGesture(location)` for a touch numbered `pointer`.
    fn start_gesture(tester: &mut WidgetTester, pointer: i64, location: Offset) -> TestPointer {
        let mut gesture = TestPointer::touch(pointer);
        tester.down(&mut gesture, location);
        gesture
    }

    /// `tester.drag(find.byType(Scrollable), offset, touchSlopY: 0.0)` for a vertical
    /// `offset`: with no slop to break the drag at, one move by all of it.
    fn drag_without_touch_slop(tester: &mut WidgetTester, pointer: i64, offset: Offset) {
        assert_eq!(offset.dx(), 0.0, "a horizontal drag is split at the slop");
        let mut gesture = start_gesture(tester, pointer, SCROLLABLE_CENTER);
        tester.move_to(&mut gesture, SCROLLABLE_CENTER + offset, true);
        tester.up(&gesture);
    }

    /// `tester.fling(find.byType(Scrollable), offset, speed)`.
    fn fling(tester: &mut WidgetTester, pointer: i64, offset: Offset, speed: f64) {
        tester.fling_from(SCROLLABLE_CENTER, offset, speed, pointer);
    }

    fn scrollable(tester: &WidgetTester) -> Handle<ScrollableState> {
        let scrollable = tester.element(find::by_type::<Scrollable>());
        scrollable
            .state_handle::<ScrollableState>(&tester.cell.borrow())
            .expect("a Scrollable has a ScrollableState")
    }

    /// `scrollable_test.dart`'s `getScrollOffset`.
    fn scroll_offset(tester: &WidgetTester) -> f64 {
        let position = scrollable(tester).position(&tester.cell.borrow());
        position.pixels(&tester.cell.borrow())
    }

    /// `scrollable_test.dart`'s `getScrollVelocity`.
    fn scroll_velocity(tester: &WidgetTester) -> f64 {
        let position = scrollable(tester).position(&tester.cell.borrow());
        tester.update(|app| {
            let activity = position.activity(app).expect("a position has an activity");
            activity.velocity(app)
        })
    }

    /// `scrollable_test.dart`'s `pumpTest` with its defaults: a vertical `CustomScrollView`
    /// over 2000 pixels that every device kind drags, with no scrollbar.
    fn pump_test(tester: &mut WidgetTester) {
        let behavior = ScrollBehaviorRef::new(NoScrollbarBehavior)
            .copy_with()
            .drag_devices(HashSet::from([
                PointerDeviceKind::Touch,
                PointerDeviceKind::Mouse,
                PointerDeviceKind::Stylus,
                PointerDeviceKind::InvertedStylus,
                PointerDeviceKind::Trackpad,
                PointerDeviceKind::Unknown,
            ]));
        let scroll_view = CustomScrollView::new().slivers([SliverToBoxAdapter::new()
            .child(SizedBox::new().height(2000.0))
            .into_widget()]);
        tester.pump_widget(Directionality::new(
            TextDirection::Ltr,
            ScrollConfiguration::new(ScrollBehaviorRef::new(behavior), scroll_view),
        ));
    }

    /// `TargetPlatformVariant(<TargetPlatform>{TargetPlatform.iOS, TargetPlatform.macOS})`.
    fn ios_and_macos() -> TargetPlatformVariant {
        TargetPlatformVariant::new([TargetPlatform::IOS, TargetPlatform::MacOS])
    }

    /// `scrollable_test.dart`: "Holding scroll".
    #[test]
    #[ignore = "settles in 2 pumps, not 3: Flutter's third is the semantics update a ScrollMetricsNotification asks for, and accessibility is deferred"]
    fn a_hold_in_overscroll_stops_the_ballistic_and_its_release_snaps_back() {
        test_widgets_variant(ios_and_macos(), |tester| {
            pump_test(tester);
            drag_without_touch_slop(tester, 1, Offset::new(0.0, 200.0));
            assert_eq!(scroll_offset(tester), -200.0);
            tester.pump(); // trigger ballistic
            tester.pump_by(Duration::from_millis(10));
            assert!(scroll_offset(tester) > -200.0);
            assert!(scroll_offset(tester) < 0.0);
            let held_position = scroll_offset(tester);
            // Hold and let go while in overscroll.
            let gesture = start_gesture(tester, 2, SCROLLABLE_CENTER);
            assert_eq!(tester.pump_and_settle(), 1);
            assert_eq!(scroll_offset(tester), held_position);
            tester.up(&gesture);
            // Once the hold is let go, it should still snap back to origin.
            assert_eq!(tester.pump_and_settle_by(Duration::from_secs(60)), 3);
            assert_eq!(scroll_offset(tester), 0.0);
        });
    }

    /// `scrollable_test.dart`: "Repeated flings builds momentum".
    #[test]
    fn repeated_flings_build_momentum_on_ios_and_macos() {
        test_widgets_variant(ios_and_macos(), |tester| {
            pump_test(tester);
            fling(tester, 1, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump(); // trigger fling
            tester.pump_by(Duration::from_millis(10));
            // Repeat the exact same motion.
            fling(tester, 2, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump();
            // On iOS, the velocity will be larger than the velocity of the last fling by a
            // non-trivial amount.
            assert!(scroll_velocity(tester) > 1100.0);
        });
    }

    /// `scrollable_test.dart`: "Repeated flings do not build momentum on Android".
    #[test]
    fn repeated_flings_do_not_build_momentum_on_android() {
        test_widgets(|tester| {
            pump_test(tester);
            fling(tester, 1, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump(); // trigger fling
            tester.pump_by(Duration::from_millis(10));
            // Repeat the exact same motion.
            fling(tester, 2, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump();
            // On Android, there is no momentum build. The final velocity is the same as the
            // velocity of the last fling.
            let velocity = scroll_velocity(tester);
            assert!((velocity - 1000.0).abs() <= 1e-10, "{velocity}");
        });
    }

    /// `scrollable_test.dart`: "A slower final fling does not apply carried momentum".
    #[test]
    fn a_slower_final_fling_does_not_apply_carried_momentum() {
        test_widgets_variant(ios_and_macos(), |tester| {
            pump_test(tester);
            fling(tester, 1, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump(); // trigger fling
            tester.pump_by(Duration::from_millis(10));
            // Repeat the exact same motion to build momentum.
            fling(tester, 2, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump(); // trigger the second fling
            tester.pump_by(Duration::from_millis(10));
            // Make a final fling that is much slower.
            fling(tester, 3, Offset::new(0.0, -DRAG_OFFSET), 200.0);
            tester.pump(); // trigger the third fling
            tester.pump_by(Duration::from_millis(10));
            // expect that there is no carried velocity
            assert!(scroll_velocity(tester) < 200.0);
        });
    }

    /// `scrollable_test.dart`: "No iOS/macOS momentum build with flings in opposite
    /// directions".
    #[test]
    fn flings_in_opposite_directions_build_no_momentum_on_ios_and_macos() {
        test_widgets_variant(ios_and_macos(), |tester| {
            pump_test(tester);
            fling(tester, 1, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump(); // trigger fling
            tester.pump_by(Duration::from_millis(10));
            // Repeat the exact same motion in the opposite direction.
            fling(tester, 2, Offset::new(0.0, DRAG_OFFSET), 1000.0);
            tester.pump();
            // The only applied velocity to the scrollable is the second fling that was in the
            // opposite direction.
            assert_eq!(scroll_velocity(tester), -1000.0);
        });
    }

    /// `scrollable_test.dart`: "No iOS/macOS momentum kept on hold gestures".
    #[test]
    fn a_hold_keeps_no_momentum_on_ios_and_macos() {
        test_widgets_variant(ios_and_macos(), |tester| {
            pump_test(tester);
            fling(tester, 1, Offset::new(0.0, -DRAG_OFFSET), 1000.0);
            tester.pump(); // trigger fling
            tester.pump_by(Duration::from_millis(10));
            assert!(scroll_velocity(tester) > 0.0);
            let gesture = start_gesture(tester, 2, SCROLLABLE_CENTER);
            tester.pump_by(Duration::from_millis(40));
            tester.up(&gesture);
            // After a hold longer than 2 frames, previous velocity is lost.
            assert_eq!(scroll_velocity(tester), 0.0);
        });
    }
}