waft-widgets 0.1.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
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
//! Flutter counterpart: `widgets/scroll_view.dart`.
//!
//! [`ScrollView`] is Dart's abstract stateless widget: a trait over a
//! [`ScrollViewData`] bag whose shared `build` body lives on [`ScrollViewBase`].
//! [`CustomScrollView`], [`BoxScrollView`], [`ListView`] and [`GridView`] follow.

use std::fmt::Debug;
use std::rc::Rc;

use waft_embedder::Clip;
use waft_foundation::App;
use waft_gestures::DragStartBehavior;
use waft_painting::{Axis, AxisDirection, EdgeInsetsGeometry};
use waft_rendering::{
    AnyViewportOffset, HitTestBehavior, ItemExtentBuilder, ScrollCacheExtent, SliverGridDelegate,
    SliverGridDelegateWithFixedCrossAxisCount, SliverGridDelegateWithMaxCrossAxisExtent,
    SliverPaintOrder,
};

use crate::framework::{
    BuildContext, IntoWidget, KeyRef, StatelessKind, StatelessWidget, WidgetRef,
};
use crate::widgets::basic::{
    SliverPadding, get_axis_direction_from_axis_reverse_and_directionality,
};
use crate::widgets::focus_manager::{FocusNodeLeaf, UnfocusDisposition, primary_focus};
use crate::widgets::focus_scope::FocusScope;
use crate::widgets::media_query::MediaQuery;
use crate::widgets::notification_listener::NotificationListener;
use crate::widgets::primary_scroll_controller::PrimaryScrollController;
use crate::widgets::scroll_configuration::{ScrollBehaviorRef, ScrollConfiguration};
use crate::widgets::scroll_controller::AnyScrollController;
use crate::widgets::scroll_delegate::{
    ChildIndexGetter, NullableIndexedWidgetBuilder, SliverChildBuilderDelegate,
    SliverChildDelegateRef, SliverChildListDelegate,
};
use crate::widgets::scroll_notification::ScrollUpdateNotification;
use crate::widgets::scroll_physics::{AlwaysScrollableScrollPhysics, ScrollPhysicsRef};
use crate::widgets::scrollable::{Scrollable, ViewportBuilder};
use crate::widgets::sliver::{
    SliverFixedExtentList, SliverGrid, SliverList, SliverVariedExtentList,
};
use crate::widgets::viewport::{ShrinkWrappingViewport, Viewport};

/// A representation of how a [`ScrollView`] should dismiss the on-screen
/// keyboard.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ScrollViewKeyboardDismissBehavior {
    /// There is no automatic dismissal of the on-screen keyboard. It is up to the
    /// client to dismiss the keyboard.
    #[default]
    Manual,

    /// The [`ScrollView`] will dismiss an on-screen keyboard when a drag begins.
    OnDrag,
}

/// The fields of Dart's `ScrollView`, which its subclasses carry.
///
/// Dart's `physics` initializer — the one that substitutes an
/// [`AlwaysScrollableScrollPhysics`] for an omitted physics — runs in
/// [`ScrollViewBase::build`] instead, because a fluent setter cannot see the
/// `primary`, `controller` and `scroll_direction` a later setter will supply.
#[derive(Clone, Debug)]
pub struct ScrollViewData {
    pub key: Option<KeyRef>,

    /// The [`Axis`] along which the scroll view's offset increases.
    ///
    /// For the direction in which active scrolling may be occurring, see
    /// `ScrollDirection`.
    ///
    /// Defaults to [`Axis::Vertical`].
    pub scroll_direction: Axis,

    /// Whether the scroll view scrolls in the reading direction.
    ///
    /// For example, if the reading direction is left-to-right and
    /// [`scroll_direction`](Self::scroll_direction) is [`Axis::Horizontal`], then the scroll
    /// view scrolls from left to right when [`reverse`](Self::reverse) is false and from
    /// right to left when it is true.
    ///
    /// Defaults to false.
    pub reverse: bool,

    /// An object that can be used to control the position to which this scroll
    /// view is scrolled.
    ///
    /// Must be `None` if [`primary`](Self::primary) is true.
    pub controller: Option<AnyScrollController>,

    /// Whether this is the primary scroll view associated with the parent
    /// [`PrimaryScrollController`].
    ///
    /// When this is true, the scroll view is scrollable even if it does not have
    /// sufficient content to actually scroll. Otherwise, by default the user can
    /// only scroll the view if it has sufficient content.
    ///
    /// Cannot be true while a controller is provided, only one controller can be
    /// associated with a scroll view.
    ///
    /// Setting to false will explicitly prevent inheriting any
    /// [`PrimaryScrollController`].
    ///
    /// Defaults to `None`. When `None`, and a controller is not provided,
    /// [`PrimaryScrollController::should_inherit`] is used to decide automatic
    /// inheritance.
    pub primary: Option<bool>,

    /// How the scroll view should respond to user input.
    ///
    /// For example, determines how the scroll view continues to animate after the
    /// user stops dragging the scroll view.
    ///
    /// Defaults to matching platform conventions. Furthermore, if
    /// [`primary`](Self::primary) is false, then the user cannot scroll if there is
    /// insufficient content to scroll, while if it is true, they can always attempt to
    /// scroll.
    ///
    /// If an explicit [`ScrollBehaviorRef`] is provided to
    /// [`scroll_behavior`](Self::scroll_behavior), the physics provided by that behavior
    /// will take precedence after this one.
    pub physics: Option<ScrollPhysicsRef>,

    /// 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.
    pub scroll_behavior: Option<ScrollBehaviorRef>,

    /// Whether the extent of the scroll view in the
    /// [`scroll_direction`](Self::scroll_direction) should be determined by the contents
    /// being viewed.
    ///
    /// If the scroll view does not shrink wrap, then the scroll view will expand
    /// to the maximum allowed size in the scroll direction. If the scroll view
    /// has unbounded constraints in the scroll direction, then this must be true.
    ///
    /// Shrink wrapping the content of the scroll view is significantly more
    /// expensive than expanding to the maximum allowed size because the content
    /// can expand and contract during scrolling, which means the size of the
    /// scroll view needs to be recomputed whenever the scroll position changes.
    ///
    /// Defaults to false.
    pub shrink_wrap: bool,

    /// The first child in the `GrowthDirection::Forward` growth direction.
    ///
    /// Children after the center will be placed in the [`AxisDirection`] determined
    /// by [`scroll_direction`](Self::scroll_direction) and [`reverse`](Self::reverse)
    /// relative to the center. Children before the center will be placed in the opposite
    /// of the axis direction relative to the center. This makes the center the inflection
    /// point of the growth direction.
    ///
    /// The center must be the key of one of the slivers built by
    /// [`ScrollView::build_slivers`].
    ///
    /// Of the built-in subclasses of [`ScrollView`], only [`CustomScrollView`]
    /// supports a center.
    pub center: Option<KeyRef>,

    /// The relative position of the zero scroll offset.
    ///
    /// For example, if the anchor is 0.5 and the [`AxisDirection`] determined by
    /// [`scroll_direction`](Self::scroll_direction) and [`reverse`](Self::reverse) is
    /// [`AxisDirection::Down`] or [`AxisDirection::Up`], then the zero scroll offset is
    /// vertically centered within the viewport. If the anchor is 1.0, and the axis
    /// direction is [`AxisDirection::Right`], then the zero scroll offset is on the left
    /// edge of the viewport.
    pub anchor: f64,

    /// Deprecated: use [`scroll_cache_extent`](Self::scroll_cache_extent) instead.
    ///
    /// The viewport has an area before and after the visible area to cache items
    /// that are about to become visible when the user scrolls.
    #[deprecated(note = "Use scroll_cache_extent instead.")]
    pub cache_extent: Option<f64>,

    /// The viewport has an area before and after the visible area to cache items
    /// that are about to become visible when the user scrolls.
    pub scroll_cache_extent: Option<ScrollCacheExtent>,

    /// The number of children that will contribute semantic information.
    ///
    /// Some subtypes of [`ScrollView`] can infer this value automatically. For
    /// example [`ListView`] will use the number of widgets in the child list,
    /// while the [`ListView::separated`] constructor will use half that amount.
    ///
    /// For [`CustomScrollView`] and other types which do not receive a builder
    /// or list of widgets, the child count must be explicitly provided. If the
    /// number is unknown or unbounded this should be left unset.
    pub semantic_child_count: Option<i32>,

    /// The order in which the viewport paints its slivers.
    ///
    /// Defaults to [`SliverPaintOrder::FirstIsTop`].
    pub paint_order: SliverPaintOrder,

    /// Determines the way that drag start behavior is handled.
    pub drag_start_behavior: DragStartBehavior,

    /// How this [`ScrollView`] will dismiss the keyboard automatically.
    ///
    /// If `None` then it will fall back to
    /// [`scroll_behavior`](Self::scroll_behavior). If that is also `None`, the inherited
    /// [`ScrollBehavior::get_keyboard_dismiss_behavior`](crate::ScrollBehavior::get_keyboard_dismiss_behavior)
    /// will be used.
    pub keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,

    /// Restoration ID to save and restore the scroll offset of the scrollable.
    pub restoration_id: Option<String>,

    /// The content will be clipped (or not) according to this option.
    ///
    /// Defaults to [`Clip::HardEdge`].
    pub clip_behavior: Clip,

    /// How to behave during hit testing when deciding how the hit test propagates
    /// to children and whether to consider targets behind this scroll view.
    ///
    /// Defaults to [`HitTestBehavior::Opaque`].
    pub hit_test_behavior: HitTestBehavior,
}

impl ScrollViewData {
    /// Dart's `ScrollView` constructor defaults.
    pub fn new() -> ScrollViewData {
        #[allow(deprecated)]
        ScrollViewData {
            key: None,
            scroll_direction: Axis::Vertical,
            reverse: false,
            controller: None,
            primary: None,
            physics: None,
            scroll_behavior: None,
            shrink_wrap: false,
            center: None,
            anchor: 0.0,
            cache_extent: None,
            scroll_cache_extent: None,
            semantic_child_count: None,
            paint_order: SliverPaintOrder::FirstIsTop,
            drag_start_behavior: DragStartBehavior::Start,
            keyboard_dismiss_behavior: None,
            restoration_id: None,
            clip_behavior: Clip::HardEdge,
            hit_test_behavior: HitTestBehavior::Opaque,
        }
    }
}

impl Default for ScrollViewData {
    fn default() -> ScrollViewData {
        ScrollViewData::new()
    }
}

/// The [`ScrollViewData`] accessors a [`ScrollView`] implementor writes; the bag lives under
/// the field `scroll_view`.
#[macro_export]
macro_rules! scroll_view_accessors {
    () => {
        fn scroll_view_data(&self) -> &$crate::ScrollViewData {
            &self.scroll_view
        }

        fn scroll_view_data_mut(&mut self) -> &mut $crate::ScrollViewData {
            &mut self.scroll_view
        }
    };
}

/// The fluent setters of the `ScrollView` named arguments every subclass takes; the ones
/// only `CustomScrollView` exposes (`scrollBehavior`, `center`, `anchor`, `paintOrder`) are
/// written on it.
#[macro_export]
macro_rules! scroll_view_setters {
    ($name:ident) => {
        /// Dart `key:`.
        pub fn key(mut self, key: $crate::KeyRef) -> $name {
            self.scroll_view.key = Some(key);
            self
        }

        /// Dart `scrollDirection:`.
        pub fn scroll_direction(mut self, scroll_direction: waft_painting::Axis) -> $name {
            self.scroll_view.scroll_direction = scroll_direction;
            self
        }

        /// Dart `reverse:`.
        pub fn reverse(mut self, reverse: bool) -> $name {
            self.scroll_view.reverse = reverse;
            self
        }

        /// Dart `controller:`.
        pub fn controller(mut self, controller: $crate::AnyScrollController) -> $name {
            debug_assert!(
                !self.scroll_view.primary.unwrap_or(false),
                "Primary ScrollViews obtain their ScrollController via inheritance from a \
                 PrimaryScrollController widget. You cannot both set primary to true and pass \
                 an explicit controller."
            );
            self.scroll_view.controller = Some(controller);
            self
        }

        /// Dart `primary:`.
        pub fn primary(mut self, primary: bool) -> $name {
            debug_assert!(
                !(self.scroll_view.controller.is_some() && primary),
                "Primary ScrollViews obtain their ScrollController via inheritance from a \
                 PrimaryScrollController widget. You cannot both set primary to true and pass \
                 an explicit controller."
            );
            self.scroll_view.primary = Some(primary);
            self
        }

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

        /// Dart `shrinkWrap:`.
        pub fn shrink_wrap(mut self, shrink_wrap: bool) -> $name {
            debug_assert!(!shrink_wrap || self.scroll_view.center.is_none());
            self.scroll_view.shrink_wrap = shrink_wrap;
            self
        }

        /// Dart `cacheExtent:`.
        #[deprecated(note = "Use scroll_cache_extent instead.")]
        pub fn cache_extent(mut self, cache_extent: f64) -> $name {
            #[allow(deprecated)]
            {
                self.scroll_view.cache_extent = Some(cache_extent);
            }
            self
        }

        /// Dart `scrollCacheExtent:`.
        pub fn scroll_cache_extent(
            mut self,
            scroll_cache_extent: waft_rendering::ScrollCacheExtent,
        ) -> $name {
            self.scroll_view.scroll_cache_extent = Some(scroll_cache_extent);
            self
        }

        /// Dart `semanticChildCount:`.
        pub fn semantic_child_count(mut self, semantic_child_count: i32) -> $name {
            debug_assert!(semantic_child_count >= 0);
            self.scroll_view.semantic_child_count = Some(semantic_child_count);
            self
        }

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

        /// Dart `keyboardDismissBehavior:`.
        pub fn keyboard_dismiss_behavior(
            mut self,
            keyboard_dismiss_behavior: $crate::ScrollViewKeyboardDismissBehavior,
        ) -> $name {
            self.scroll_view.keyboard_dismiss_behavior = Some(keyboard_dismiss_behavior);
            self
        }

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

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

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

/// A widget that combines a `Scrollable` and a [`Viewport`] to create an
/// interactive scrolling pane of content in one dimension.
///
/// Scrollable widgets consist of three pieces:
///
///  1. A `Scrollable` widget, which listens for various user gestures and
///     implements the interaction design for scrolling.
///  2. A viewport widget, such as [`Viewport`] or [`ShrinkWrappingViewport`], which
///     implements the visual design for scrolling by displaying only a portion
///     of the widgets inside the scroll view.
///  3. One or more slivers, which are widgets that can be composed to create
///     various scrolling effects, such as lists, grids, and expanding headers.
///
/// [`ScrollView`] helps orchestrate these pieces by creating the `Scrollable` and
/// the viewport and deferring to its implementor to create the slivers.
///
/// Dart's abstract `ScrollView` is this trait over a [`ScrollViewData`] bag; the shared
/// `build` body lives on [`ScrollViewBase`], which an implementor's
/// [`StatelessWidget::build`] calls.
///
/// ## Persisting the scroll position during a session
///
/// Scroll views attempt to persist their scroll position using `PageStorage`.
/// This can be disabled by setting
/// [`ScrollControllerLeaf::keep_scroll_offset`](crate::ScrollControllerLeaf::keep_scroll_offset)
/// to false on the controller.
pub trait ScrollView: Clone + Debug + Sized + 'static {
    /// The [`ScrollViewData`] bag ([`scroll_view_accessors!`](crate::scroll_view_accessors)).
    fn scroll_view_data(&self) -> &ScrollViewData;

    /// The [`ScrollViewData`] bag, mutably.
    fn scroll_view_data_mut(&mut self) -> &mut ScrollViewData;

    /// Returns the [`AxisDirection`] in which the scroll view scrolls.
    ///
    /// Combines the [`ScrollViewData::scroll_direction`] with the
    /// [`ScrollViewData::reverse`] boolean to obtain the concrete [`AxisDirection`].
    ///
    /// If the scroll direction is [`Axis::Horizontal`], the ambient `Directionality` is
    /// also considered when selecting the concrete [`AxisDirection`].
    fn get_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
        ScrollViewBase::get_direction(self, app, context)
    }

    /// Build the list of widgets to place inside the viewport.
    ///
    /// Implementors override this method to build the slivers for the inside of
    /// the viewport.
    fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef>;

    /// Build the viewport.
    ///
    /// Implementors may override this method to change how the viewport is built.
    /// The default implementation uses a [`ShrinkWrappingViewport`] if
    /// [`ScrollViewData::shrink_wrap`] is true, and a regular [`Viewport`] otherwise.
    ///
    /// The `offset` argument is the value obtained from
    /// [`Scrollable::viewport_builder`].
    ///
    /// The `axis_direction` argument is the value obtained from
    /// [`get_direction`](Self::get_direction).
    ///
    /// The `slivers` argument is the value obtained from
    /// [`build_slivers`](Self::build_slivers).
    fn build_viewport(
        &self,
        app: &mut App,
        context: BuildContext,
        offset: AnyViewportOffset,
        axis_direction: AxisDirection,
        slivers: Vec<WidgetRef>,
    ) -> WidgetRef {
        ScrollViewBase::build_viewport(self, app, context, offset, axis_direction, slivers)
    }
}

/// The shared bodies of Dart's `ScrollView`: call one where Dart writes `super.…`.
pub struct ScrollViewBase;

impl ScrollViewBase {
    /// See [`ScrollView::get_direction`].
    pub fn get_direction<V: ScrollView>(
        view: &V,
        app: &mut App,
        context: BuildContext,
    ) -> AxisDirection {
        let data = view.scroll_view_data();
        get_axis_direction_from_axis_reverse_and_directionality(
            app,
            context,
            data.scroll_direction,
            data.reverse,
        )
    }

    /// See [`ScrollView::build_viewport`].
    pub fn build_viewport<V: ScrollView>(
        view: &V,
        app: &mut App,
        context: BuildContext,
        offset: AnyViewportOffset,
        axis_direction: AxisDirection,
        slivers: Vec<WidgetRef>,
    ) -> WidgetRef {
        let _ = (app, context);
        let data = view.scroll_view_data();
        #[allow(deprecated)]
        let effective_scroll_cache_extent = data
            .scroll_cache_extent
            .or(data.cache_extent.map(ScrollCacheExtent::Pixels));
        if data.shrink_wrap {
            let mut viewport = ShrinkWrappingViewport::new(offset)
                .axis_direction(axis_direction)
                .slivers(slivers)
                .paint_order(data.paint_order)
                .clip_behavior(data.clip_behavior);
            if let Some(cache_extent) = effective_scroll_cache_extent {
                viewport = viewport.scroll_cache_extent(cache_extent);
            }
            return viewport.into_widget();
        }
        let mut viewport = Viewport::new(offset)
            .axis_direction(axis_direction)
            .slivers(slivers)
            .anchor(data.anchor)
            .paint_order(data.paint_order)
            .clip_behavior(data.clip_behavior);
        if let Some(cache_extent) = effective_scroll_cache_extent {
            viewport = viewport.scroll_cache_extent(cache_extent);
        }
        if let Some(center) = data.center.clone() {
            viewport = viewport.center(center);
        }
        viewport.into_widget()
    }

    /// Dart's `ScrollView.build`, which an implementor's [`StatelessWidget::build`] calls.
    pub fn build<V: ScrollView>(view: &V, app: &mut App, context: BuildContext) -> WidgetRef {
        let slivers = view.build_slivers(app, context);
        let axis_direction = view.get_direction(app, context);

        let data = view.scroll_view_data().clone();
        let effective_primary = data.primary.unwrap_or_else(|| {
            data.controller.is_none()
                && PrimaryScrollController::should_inherit(app, context, data.scroll_direction)
        });

        let scroll_controller = if effective_primary {
            PrimaryScrollController::maybe_of(app, context)
        } else {
            data.controller
        };

        let this = view.clone();
        let viewport_builder: ViewportBuilder = Rc::new(move |app, context, offset| {
            this.build_viewport(app, context, offset, axis_direction, slivers.clone())
        });

        let mut scrollable = Scrollable::new(viewport_builder)
            .axis_direction(axis_direction)
            .drag_start_behavior(data.drag_start_behavior)
            .hit_test_behavior(data.hit_test_behavior)
            .clip_behavior(data.clip_behavior);
        if let Some(controller) = scroll_controller {
            scrollable = scrollable.controller(controller);
        }
        if let Some(physics) = ScrollViewBase::effective_physics(view) {
            scrollable = scrollable.physics(physics);
        }
        if let Some(scroll_behavior) = data.scroll_behavior.clone() {
            scrollable = scrollable.scroll_behavior(scroll_behavior);
        }
        if let Some(restoration_id) = data.restoration_id.clone() {
            scrollable = scrollable.restoration_id(restoration_id);
        }

        let scrollable_result = if effective_primary && scroll_controller.is_some() {
            // Further descendant scroll views will not inherit the same
            // `PrimaryScrollController`.
            PrimaryScrollController::none(scrollable).into_widget()
        } else {
            scrollable.into_widget()
        };

        let effective_keyboard_dismiss_behavior = data
            .keyboard_dismiss_behavior
            .or_else(|| {
                data.scroll_behavior
                    .as_ref()
                    .map(|behavior| behavior.get_keyboard_dismiss_behavior(app, context))
            })
            .unwrap_or_else(|| {
                ScrollConfiguration::of(app, context).get_keyboard_dismiss_behavior(app, context)
            });

        if effective_keyboard_dismiss_behavior == ScrollViewKeyboardDismissBehavior::OnDrag {
            NotificationListener::<ScrollUpdateNotification>::new(scrollable_result)
                .on_notification(move |app, notification: &ScrollUpdateNotification| {
                    let current_scope = FocusScope::of(app, context, true).as_node();
                    if notification.drag_details.is_some()
                        && !current_scope.has_primary_focus(app)
                        && current_scope.has_focus(app)
                        && let Some(primary) = primary_focus(app)
                    {
                        primary.unfocus(app, UnfocusDisposition::Scope);
                    }
                    false
                })
                .into_widget()
        } else {
            scrollable_result
        }
    }

    /// Dart's `physics` constructor initializer: an omitted physics becomes an
    /// [`AlwaysScrollableScrollPhysics`] for a primary scroll view, and for a vertical one
    /// that neither names a controller nor opts out of inheriting the primary one.
    fn effective_physics<V: ScrollView>(view: &V) -> Option<ScrollPhysicsRef> {
        let data = view.scroll_view_data();
        if let Some(physics) = data.physics.clone() {
            return Some(physics);
        }
        let implied = data.primary.unwrap_or(false)
            || (data.primary.is_none()
                && data.controller.is_none()
                && data.scroll_direction == Axis::Vertical);
        implied.then(|| Rc::new(AlwaysScrollableScrollPhysics::new()) as ScrollPhysicsRef)
    }
}

/// A [`ScrollView`] that combines multiple [`slivers`](Self::slivers) in one scrollable view.
///
/// A [`CustomScrollView`] lets you combine lists, grids, and other widgets in a
/// single scrollable view by supplying slivers directly. Slivers can
/// represent lists, grids, and expanding headers. Widgets that use the box
/// layout model can be included using a `SliverToBoxAdapter`.
///
/// ```ignore
/// CustomScrollView::new().slivers([
///     SliverToBoxAdapter::new().child(header).into_widget(),
///     SliverList::list(items).into_widget(),
/// ])
/// ```
#[derive(Clone, Debug, Default)]
pub struct CustomScrollView {
    scroll_view: ScrollViewData,

    /// The slivers to place inside the viewport.
    ///
    /// A _sliver_ is a widget backed by a `RenderSliver`, i.e. one that implements the
    /// constraint/geometry protocol that uses `SliverConstraints` and `SliverGeometry`.
    /// This is as distinct from those widgets that are backed by `RenderBox`, which use
    /// `BoxConstraints` and `Size` respectively, and are known as box widgets.
    ///
    /// While boxes are much more straightforward (implementing a simple two-dimensional
    /// Cartesian layout system), slivers are much more powerful, and are optimized for
    /// one-axis scrolling environments.
    ///
    /// In general, slivers always wrap box widgets to actually render anything; the sliver
    /// part of the equation is mostly about how these boxes should be laid out in a
    /// viewport.
    pub slivers: Vec<WidgetRef>,
}

impl CustomScrollView {
    /// Creates a [`ScrollView`] that combines multiple slivers in one scrollable
    /// view.
    pub fn new() -> CustomScrollView {
        CustomScrollView {
            scroll_view: ScrollViewData::new(),
            slivers: Vec::new(),
        }
    }

    crate::scroll_view_setters!(CustomScrollView);

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

    /// Dart `CustomScrollView(center:)`.
    pub fn center(mut self, center: KeyRef) -> CustomScrollView {
        debug_assert!(!self.scroll_view.shrink_wrap);
        self.scroll_view.center = Some(center);
        self
    }

    /// Dart `CustomScrollView(anchor:)`.
    pub fn anchor(mut self, anchor: f64) -> CustomScrollView {
        debug_assert!((0.0..=1.0).contains(&anchor));
        self.scroll_view.anchor = anchor;
        self
    }

    /// Dart `CustomScrollView(paintOrder:)`.
    pub fn paint_order(mut self, paint_order: SliverPaintOrder) -> CustomScrollView {
        self.scroll_view.paint_order = paint_order;
        self
    }

    /// Dart `CustomScrollView(slivers:)`.
    pub fn slivers(mut self, slivers: impl IntoIterator<Item = WidgetRef>) -> CustomScrollView {
        self.slivers = slivers.into_iter().collect();
        self
    }
}

impl ScrollView for CustomScrollView {
    crate::scroll_view_accessors!();

    fn build_slivers(&self, _app: &mut App, _context: BuildContext) -> Vec<WidgetRef> {
        self.slivers.clone()
    }
}

impl StatelessWidget for CustomScrollView {
    fn key(&self) -> Option<&KeyRef> {
        self.scroll_view.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        ScrollViewBase::build(self, app, context)
    }
}

/// The fields Dart's `BoxScrollView` adds to a [`ScrollView`].
#[derive(Clone, Debug, Default)]
pub struct BoxScrollViewData {
    /// The amount of space by which to inset the children.
    pub padding: Option<EdgeInsetsGeometry>,
}

impl BoxScrollViewData {
    /// Dart's `BoxScrollView` constructor defaults.
    pub fn new() -> BoxScrollViewData {
        BoxScrollViewData { padding: None }
    }
}

/// The [`BoxScrollViewData`] accessors a [`BoxScrollView`] implementor writes; the bag lives
/// under the field `box_scroll_view`.
#[macro_export]
macro_rules! box_scroll_view_accessors {
    () => {
        fn box_scroll_view_data(&self) -> &$crate::BoxScrollViewData {
            &self.box_scroll_view
        }

        fn box_scroll_view_data_mut(&mut self) -> &mut $crate::BoxScrollViewData {
            &mut self.box_scroll_view
        }
    };
}

/// A [`ScrollView`] that uses a single child layout model.
///
/// Scroll views are often decorated with scrollbars and overscroll indicators,
/// which are managed by the inherited
/// [`ScrollBehavior`](crate::ScrollBehavior). Placing a [`ScrollConfiguration`] above a
/// scroll view can modify these behaviors for that scroll view.
///
/// The shared `buildSlivers` body lives on [`BoxScrollViewBase`], which an implementor's
/// [`ScrollView::build_slivers`] calls.
pub trait BoxScrollView: ScrollView {
    /// The [`BoxScrollViewData`] bag
    /// ([`box_scroll_view_accessors!`](crate::box_scroll_view_accessors)).
    fn box_scroll_view_data(&self) -> &BoxScrollViewData;

    /// The [`BoxScrollViewData`] bag, mutably.
    fn box_scroll_view_data_mut(&mut self) -> &mut BoxScrollViewData;

    /// Implementors override this method to build the layout model.
    fn build_child_layout(&self, app: &mut App, context: BuildContext) -> WidgetRef;
}

/// The shared bodies of Dart's `BoxScrollView`: call one where Dart writes `super.…`.
pub struct BoxScrollViewBase;

impl BoxScrollViewBase {
    /// Dart's `BoxScrollView.buildSlivers`, which an implementor's
    /// [`ScrollView::build_slivers`] calls.
    pub fn build_slivers<V: BoxScrollView>(
        view: &V,
        app: &mut App,
        context: BuildContext,
    ) -> Vec<WidgetRef> {
        let mut sliver = view.build_child_layout(app, context);
        let padding = view.box_scroll_view_data().padding;
        let mut effective_padding = padding;
        if padding.is_none()
            && let Some(media_query) = MediaQuery::maybe_of(app, context)
        {
            // Automatically pad sliver with padding from `MediaQuery`.
            let media_query_horizontal_padding =
                media_query
                    .padding
                    .copy_with(None, Some(0.0), None, Some(0.0));
            let media_query_vertical_padding =
                media_query
                    .padding
                    .copy_with(Some(0.0), None, Some(0.0), None);
            let vertical = view.scroll_view_data().scroll_direction == Axis::Vertical;
            // Consume the main axis padding with a `SliverPadding`.
            effective_padding = Some(EdgeInsetsGeometry::from(if vertical {
                media_query_vertical_padding
            } else {
                media_query_horizontal_padding
            }));
            // Leave behind the cross axis padding.
            sliver = MediaQuery::new(
                media_query.copy_with().padding(if vertical {
                    media_query_horizontal_padding
                } else {
                    media_query_vertical_padding
                }),
                sliver,
            )
            .into_widget();
        }

        if let Some(effective_padding) = effective_padding {
            sliver = SliverPadding::new(effective_padding)
                .sliver(sliver)
                .into_widget();
        }
        vec![sliver]
    }
}

/// A scrollable list of widgets arranged linearly.
///
/// [`ListView`] is the most commonly used scrolling widget. It displays its
/// children one after another in the scroll direction. In the cross axis, the
/// children are required to fill the [`ListView`].
///
/// If non-`None`, the [`item_extent`](Self::item_extent) forces the children to have the
/// given extent in the scroll direction. Specifying an item extent is more efficient than
/// letting the children determine their own extent because the scrolling machinery can make
/// use of the foreknowledge of the children's extent to save work, for example when the
/// scroll position changes drastically.
///
/// There are four ways to construct a [`ListView`]:
///
///  1. [`ListView::new`] takes an explicit list of children through the
///     [`children`](Self::children) setter. This is appropriate for list views with a small
///     number of children because constructing the list requires doing work for every child
///     that could possibly be displayed in the list view instead of just those children that
///     are actually visible.
///
///  2. [`ListView::builder`] takes an item builder, which builds the children on demand.
///     This is appropriate for list views with a large (or infinite) number of children
///     because the builder is called only for those children that are actually visible.
///
///  3. [`ListView::separated`] takes two builders: `item_builder` builds child items on
///     demand, and `separator_builder` similarly builds separator children which appear in
///     between the child items. This is appropriate for list views with a fixed number of
///     children.
///
///  4. [`ListView::custom`] takes a
///     [`SliverChildDelegateRef`], which provides the ability to customize additional
///     aspects of the child model.
///
/// By default, a [`ListView`] will automatically pad the list's scrollable
/// extremities to avoid partial obstructions indicated by the `MediaQuery`'s
/// padding. To avoid this behavior, override with a zero
/// [`padding`](Self::padding).
///
/// ## Transitioning to [`CustomScrollView`]
///
/// A [`ListView`] is basically a [`CustomScrollView`] with a single [`SliverList`] in
/// its [`CustomScrollView::slivers`] property. The
/// [`padding`](Self::padding) corresponds to having a `SliverPadding` in the slivers
/// instead of the list itself, and having the [`SliverList`] instead be a child of the
/// `SliverPadding`.
pub struct ListView {
    scroll_view: ScrollViewData,
    box_scroll_view: BoxScrollViewData,

    /// If non-`None`, forces the children to have the given extent in the scroll
    /// direction.
    ///
    /// Specifying an item extent is more efficient than letting the children
    /// determine their own extent because the scrolling machinery can make use of
    /// the foreknowledge of the children's extent to save work, for example when
    /// the scroll position changes drastically.
    pub item_extent: Option<f64>,

    /// If non-`None`, forces the children to have the corresponding extent returned
    /// by the builder.
    ///
    /// Specifying an item extent builder is more efficient than letting the
    /// children determine their own extent because the scrolling machinery can
    /// make use of the foreknowledge of the children's extent to save work, for
    /// example when the scroll position changes drastically.
    pub item_extent_builder: Option<ItemExtentBuilder>,

    /// A delegate that provides the children for the [`ListView`].
    ///
    /// The [`SliverList::delegate`] property corresponds to this one.
    pub children_delegate: SliverChildDelegateRef,

    // Dart's default constructor's `children` and `add*` arguments, kept so that whichever
    // of their setters runs last can rebuild `children_delegate` out of all of them. `None`
    // for the constructors that take (or build) a delegate.
    list_arguments: Option<ListArguments>,
}

/// The `SliverChildListDelegate` arguments of the Dart constructors that take children:
/// `ListView`'s default one, and `GridView`'s default, `count` and `extent` ones.
#[derive(Clone, Debug)]
struct ListArguments {
    children: Vec<WidgetRef>,
    add_automatic_keep_alives: bool,
    add_repaint_boundaries: bool,
    add_semantic_indexes: bool,
}

impl ListArguments {
    fn new() -> ListArguments {
        ListArguments {
            children: Vec::new(),
            add_automatic_keep_alives: true,
            add_repaint_boundaries: true,
            add_semantic_indexes: true,
        }
    }

    fn into_delegate(self) -> SliverChildDelegateRef {
        SliverChildListDelegate::new(self.children)
            .add_automatic_keep_alives(self.add_automatic_keep_alives)
            .add_repaint_boundaries(self.add_repaint_boundaries)
            .add_semantic_indexes(self.add_semantic_indexes)
            .into_delegate()
    }
}

/// The fluent setters of the `SliverChildListDelegate` arguments, on a scroll view whose
/// `list_arguments` holds them; each rebuilds `children_delegate` out of all of them.
macro_rules! list_arguments_setters {
    ($name:ident) => {
        /// Dart `children:`.
        ///
        /// The children also fill in [`ScrollViewData::semantic_child_count`] while it still
        /// holds the constructor's default, as Dart's `semanticChildCount ?? children.length`
        /// does.
        pub fn children(self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
            let children: Vec<WidgetRef> = children.into_iter().collect();
            let count = children.len() as i32;
            let mut this = self.with_list_arguments(|arguments| arguments.children = children);
            if this.scroll_view.semantic_child_count == Some(0) {
                this.scroll_view.semantic_child_count = Some(count);
            }
            this
        }

        /// Dart `addAutomaticKeepAlives:` on a constructor that takes children.
        pub fn add_automatic_keep_alives(self, value: bool) -> $name {
            self.with_list_arguments(|arguments| arguments.add_automatic_keep_alives = value)
        }

        /// Dart `addRepaintBoundaries:` on a constructor that takes children.
        pub fn add_repaint_boundaries(self, value: bool) -> $name {
            self.with_list_arguments(|arguments| arguments.add_repaint_boundaries = value)
        }

        /// Dart `addSemanticIndexes:` on a constructor that takes children.
        pub fn add_semantic_indexes(self, value: bool) -> $name {
            self.with_list_arguments(|arguments| arguments.add_semantic_indexes = value)
        }

        /// Applies one of the constructor's delegate arguments and rebuilds
        /// [`children_delegate`](Self::children_delegate) out of all of them.
        fn with_list_arguments(mut self, apply: impl FnOnce(&mut ListArguments)) -> $name {
            let mut arguments = self.list_arguments.expect(concat!(
                "the children and add* setters belong to the ",
                stringify!($name),
                " constructors that take children"
            ));
            apply(&mut arguments);
            self.children_delegate = arguments.clone().into_delegate();
            self.list_arguments = Some(arguments);
            self
        }
    };
}

impl ListView {
    /// Creates a scrollable, linear array of widgets from an explicit list, which
    /// the [`children`](Self::children) setter supplies.
    ///
    /// This constructor is appropriate for list views with a small number of
    /// children because constructing the list requires doing work for every
    /// child that could possibly be displayed in the list view instead of just
    /// those children that are actually visible.
    ///
    /// It is usually more efficient to create children on demand using
    /// [`ListView::builder`].
    pub fn new() -> ListView {
        let list_arguments = ListArguments::new();
        ListView {
            scroll_view: ScrollViewData {
                semantic_child_count: Some(0),
                ..ScrollViewData::new()
            },
            box_scroll_view: BoxScrollViewData::new(),
            item_extent: None,
            item_extent_builder: None,
            children_delegate: list_arguments.clone().into_delegate(),
            list_arguments: Some(list_arguments),
        }
    }

    /// Creates a scrollable, linear array of widgets that are created on demand.
    ///
    /// This constructor is appropriate for list views with a large (or infinite)
    /// number of children because the builder is called only for those children
    /// that are actually visible.
    ///
    /// The item builder will be called only with indices greater than or equal to
    /// zero and less than [`item_count`](ListViewBuilder::item_count).
    pub fn builder(
        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
    ) -> ListViewBuilder {
        ListViewBuilder::new(Rc::new(item_builder))
    }

    /// Creates a fixed-length scrollable linear array of list "items" separated
    /// by list item "separators".
    ///
    /// This constructor is appropriate for list views with a large number of
    /// item and separator children because the builders are only called for
    /// the children that are actually visible.
    ///
    /// The `separator_builder` is similar to `item_builder`, except it is the widget that
    /// gets placed between `item_builder(context, index)` and
    /// `item_builder(context, index + 1)`.
    pub fn separated(
        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
        separator_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
        item_count: i32,
    ) -> ListViewSeparated {
        ListViewSeparated::new(
            Rc::new(item_builder),
            Rc::new(separator_builder),
            item_count,
        )
    }

    /// Creates a scrollable, linear array of widgets with a custom child model.
    ///
    /// For example, a custom child model can control the algorithm used to
    /// estimate the size of children that are not actually visible.
    pub fn custom(children_delegate: SliverChildDelegateRef) -> ListView {
        ListView {
            scroll_view: ScrollViewData::new(),
            box_scroll_view: BoxScrollViewData::new(),
            item_extent: None,
            item_extent_builder: None,
            children_delegate,
            list_arguments: None,
        }
    }

    crate::scroll_view_setters!(ListView);

    /// Dart `ListView(padding:)`.
    pub fn padding(mut self, padding: EdgeInsetsGeometry) -> ListView {
        self.box_scroll_view.padding = Some(padding);
        self
    }

    /// Dart `ListView(itemExtent:)`.
    pub fn item_extent(mut self, item_extent: f64) -> ListView {
        debug_assert!(
            self.item_extent_builder.is_none(),
            "You can only pass one of itemExtent and itemExtentBuilder."
        );
        self.item_extent = Some(item_extent);
        self
    }

    /// Dart `ListView(itemExtentBuilder:)`.
    pub fn item_extent_builder(mut self, item_extent_builder: ItemExtentBuilder) -> ListView {
        debug_assert!(
            self.item_extent.is_none(),
            "You can only pass one of itemExtent and itemExtentBuilder."
        );
        self.item_extent_builder = Some(item_extent_builder);
        self
    }

    list_arguments_setters!(ListView);
}

impl Default for ListView {
    fn default() -> ListView {
        ListView::new()
    }
}

impl ScrollView for ListView {
    crate::scroll_view_accessors!();

    fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
        BoxScrollViewBase::build_slivers(self, app, context)
    }
}

impl BoxScrollView for ListView {
    crate::box_scroll_view_accessors!();

    fn build_child_layout(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        if let Some(item_extent) = self.item_extent {
            return SliverFixedExtentList::new(self.children_delegate.clone(), item_extent)
                .into_widget();
        }
        if let Some(item_extent_builder) = self.item_extent_builder.clone() {
            return SliverVariedExtentList::new(
                self.children_delegate.clone(),
                item_extent_builder,
            )
            .into_widget();
        }
        SliverList::new(self.children_delegate.clone()).into_widget()
    }
}

impl StatelessWidget for ListView {
    fn key(&self) -> Option<&KeyRef> {
        self.scroll_view.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        ScrollViewBase::build(self, app, context)
    }
}

/// Dart's `ListView.builder(..)` arguments; the value converts to the [`ListView`].
pub struct ListViewBuilder {
    list_view: ListView,
    delegate: SliverChildBuilderDelegate,
}

impl ListViewBuilder {
    fn new(item_builder: NullableIndexedWidgetBuilder) -> ListViewBuilder {
        ListViewBuilder {
            list_view: ListView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate()),
            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
        }
    }

    /// Dart `itemCount:`, which also fills in
    /// [`ScrollViewData::semantic_child_count`], as Dart's
    /// `semanticChildCount ?? itemCount` does.
    pub fn item_count(mut self, item_count: i32) -> ListViewBuilder {
        debug_assert!(item_count >= 0);
        self.delegate = self.delegate.child_count(item_count);
        if self.list_view.scroll_view.semantic_child_count.is_none() {
            self.list_view.scroll_view.semantic_child_count = Some(item_count);
        }
        self
    }

    /// Dart `findChildIndexCallback:`.
    pub fn find_child_index_callback(
        mut self,
        find_child_index_callback: ChildIndexGetter,
    ) -> ListViewBuilder {
        self.delegate = self
            .delegate
            .find_child_index_callback(find_child_index_callback);
        self
    }

    /// Dart `addAutomaticKeepAlives:`.
    pub fn add_automatic_keep_alives(mut self, value: bool) -> ListViewBuilder {
        self.delegate = self.delegate.add_automatic_keep_alives(value);
        self
    }

    /// Dart `addRepaintBoundaries:`.
    pub fn add_repaint_boundaries(mut self, value: bool) -> ListViewBuilder {
        self.delegate = self.delegate.add_repaint_boundaries(value);
        self
    }

    /// Dart `addSemanticIndexes:`.
    pub fn add_semantic_indexes(mut self, value: bool) -> ListViewBuilder {
        self.delegate = self.delegate.add_semantic_indexes(value);
        self
    }

    /// The [`ListView`] this builder describes.
    pub fn build(self) -> ListView {
        ListView {
            children_delegate: self.delegate.into_delegate(),
            ..self.list_view
        }
    }
}

/// Dart's `ListView.separated(..)` arguments; the value converts to the [`ListView`].
pub struct ListViewSeparated {
    list_view: ListView,
    delegate: SliverChildBuilderDelegate,
}

impl ListViewSeparated {
    fn new(
        item_builder: NullableIndexedWidgetBuilder,
        separator_builder: NullableIndexedWidgetBuilder,
        item_count: i32,
    ) -> ListViewSeparated {
        debug_assert!(item_count >= 0);
        let delegate = SliverChildBuilderDelegate::from_builder(Rc::new(
            move |app: &mut App, context, index: i32| {
                let item_index = index.div_euclid(2);
                if index % 2 == 0 {
                    item_builder(app, context, item_index)
                } else {
                    separator_builder(app, context, item_index)
                }
            },
        ))
        .child_count(compute_actual_child_count(item_count))
        .semantic_index_callback(Rc::new(|_widget, index| {
            (index % 2 == 0).then_some(index / 2)
        }));
        ListViewSeparated {
            list_view: ListView {
                scroll_view: ScrollViewData {
                    semantic_child_count: Some(item_count),
                    ..ScrollViewData::new()
                },
                ..ListView::custom(SliverChildListDelegate::new(Vec::new()).into_delegate())
            },
            delegate,
        }
    }

    /// Dart `findItemIndexCallback:`, which reports item indices (separators excluded).
    pub fn find_item_index_callback(
        mut self,
        find_item_index_callback: ChildIndexGetter,
    ) -> ListViewSeparated {
        self.delegate = self.delegate.find_child_index_callback(Rc::new(move |key| {
            find_item_index_callback(key).map(|item_index| item_index * 2)
        }));
        self
    }

    /// Dart `addAutomaticKeepAlives:`.
    pub fn add_automatic_keep_alives(mut self, value: bool) -> ListViewSeparated {
        self.delegate = self.delegate.add_automatic_keep_alives(value);
        self
    }

    /// Dart `addRepaintBoundaries:`.
    pub fn add_repaint_boundaries(mut self, value: bool) -> ListViewSeparated {
        self.delegate = self.delegate.add_repaint_boundaries(value);
        self
    }

    /// Dart `addSemanticIndexes:`.
    pub fn add_semantic_indexes(mut self, value: bool) -> ListViewSeparated {
        self.delegate = self.delegate.add_semantic_indexes(value);
        self
    }

    /// The [`ListView`] this value describes.
    pub fn build(self) -> ListView {
        ListView {
            children_delegate: self.delegate.into_delegate(),
            ..self.list_view
        }
    }
}

impl IntoWidget<StatelessKind> for ListViewBuilder {
    fn into_widget(self) -> WidgetRef {
        self.build().into_widget()
    }
}

impl IntoWidget<StatelessKind> for ListViewSeparated {
    fn into_widget(self) -> WidgetRef {
        self.build().into_widget()
    }
}

/// Helper method to compute the actual child count for the separated constructor.
fn compute_actual_child_count(item_count: i32) -> i32 {
    (item_count * 2 - 1).max(0)
}

impl Clone for ListView {
    fn clone(&self) -> ListView {
        ListView {
            scroll_view: self.scroll_view.clone(),
            box_scroll_view: self.box_scroll_view.clone(),
            item_extent: self.item_extent,
            item_extent_builder: self.item_extent_builder.clone(),
            children_delegate: self.children_delegate.clone(),
            list_arguments: self.list_arguments.clone(),
        }
    }
}

impl Debug for ListView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ListView")
            .field("itemExtent", &self.item_extent)
            .field("childrenDelegate", &self.children_delegate)
            .finish_non_exhaustive()
    }
}

/// A scrollable, 2D array of widgets.
///
/// The main axis direction of a grid is the direction in which it scrolls (the
/// [`ScrollViewData::scroll_direction`]).
///
/// The most commonly used grid layouts are [`GridView::count`], which creates a layout with a
/// fixed number of tiles in the cross axis, and [`GridView::extent`], which creates a layout
/// with tiles that have a maximum cross-axis extent. A custom [`SliverGridDelegate`] can
/// produce an arbitrary 2D arrangement of children, including arrangements that are unaligned
/// or overlapping.
///
/// To create a grid with a large (or infinite) number of children, use the
/// [`GridView::builder`] constructor with either a [`SliverGridDelegateWithFixedCrossAxisCount`]
/// or a [`SliverGridDelegateWithMaxCrossAxisExtent`] for the grid delegate.
///
/// To use a custom `SliverChildDelegate`, use [`GridView::custom`].
///
/// To create a linear array of children, use a [`ListView`].
///
/// To control the initial scroll offset of the scroll view, provide a
/// [`controller`](Self::controller) with its `ScrollController::initial_scroll_offset`
/// property set.
///
/// ## Transitioning to [`CustomScrollView`]
///
/// A [`GridView`] is basically a [`CustomScrollView`] with a single [`SliverGrid`] in its
/// [`CustomScrollView::slivers`] property.
///
/// By default, [`GridView`] will automatically pad the limits of the grid's scrollable to avoid
/// partial obstructions indicated by `MediaQuery`'s padding. To avoid this behavior, override
/// with a zero [`padding`](Self::padding) property.
pub struct GridView {
    scroll_view: ScrollViewData,
    box_scroll_view: BoxScrollViewData,

    /// A delegate that controls the layout of the children within the [`GridView`].
    ///
    /// The [`GridView::new`], [`GridView::builder`], and [`GridView::custom`] constructors let
    /// you specify this delegate explicitly. The other constructors create a
    /// [`grid_delegate`](Self::grid_delegate) implicitly.
    pub grid_delegate: Rc<dyn SliverGridDelegate>,

    /// A delegate that provides the children for the [`GridView`].
    ///
    /// The [`GridView::custom`] constructor lets you specify this delegate explicitly. The
    /// other constructors create a [`children_delegate`](Self::children_delegate) that wraps
    /// the given child list.
    pub children_delegate: SliverChildDelegateRef,

    // As `ListView`'s: the arguments of the constructors that take children, for their setters.
    list_arguments: Option<ListArguments>,
}

impl GridView {
    /// Creates a scrollable, 2D array of widgets with a custom [`SliverGridDelegate`], from an
    /// explicit list of children that the [`children`](Self::children) setter supplies.
    pub fn new(grid_delegate: Rc<dyn SliverGridDelegate>) -> GridView {
        let list_arguments = ListArguments::new();
        GridView {
            scroll_view: ScrollViewData {
                semantic_child_count: Some(0),
                ..ScrollViewData::new()
            },
            box_scroll_view: BoxScrollViewData::new(),
            grid_delegate,
            children_delegate: list_arguments.clone().into_delegate(),
            list_arguments: Some(list_arguments),
        }
    }

    /// Creates a scrollable, 2D array of widgets that are created on demand.
    ///
    /// This constructor is appropriate for grid views with a large (or infinite) number of
    /// children because the builder is called only for those children that are actually
    /// visible.
    ///
    /// Providing a non-`None` [`item_count`](GridViewBuilder::item_count) improves the ability
    /// of the [`GridView`] to estimate the maximum scroll extent.
    ///
    /// The item builder will be called only with indices greater than or equal to zero and less
    /// than the item count.
    pub fn builder(
        grid_delegate: Rc<dyn SliverGridDelegate>,
        item_builder: impl Fn(&mut App, BuildContext, i32) -> Option<WidgetRef> + 'static,
    ) -> GridViewBuilder {
        GridViewBuilder::new(grid_delegate, Rc::new(item_builder))
    }

    /// Creates a scrollable, 2D array of widgets with both a custom [`SliverGridDelegate`] and a
    /// custom `SliverChildDelegate`.
    ///
    /// To use an item builder callback to build children, either use a
    /// [`SliverChildBuilderDelegate`] or use the [`GridView::builder`] constructor.
    pub fn custom(
        grid_delegate: Rc<dyn SliverGridDelegate>,
        children_delegate: SliverChildDelegateRef,
    ) -> GridView {
        GridView {
            scroll_view: ScrollViewData::new(),
            box_scroll_view: BoxScrollViewData::new(),
            grid_delegate,
            children_delegate,
            list_arguments: None,
        }
    }

    /// Creates a scrollable, 2D array of widgets with a fixed number of tiles in the cross axis.
    ///
    /// Uses a [`SliverGridDelegateWithFixedCrossAxisCount`] as the
    /// [`grid_delegate`](Self::grid_delegate).
    ///
    /// See also:
    ///
    ///  * [`SliverGrid::count`], the equivalent constructor for [`SliverGrid`].
    pub fn count(cross_axis_count: i32) -> GridViewCount {
        let grid_delegate = SliverGridDelegateWithFixedCrossAxisCount::new(cross_axis_count);
        GridViewCount {
            grid_view: GridView::new(Rc::new(grid_delegate.clone())),
            grid_delegate,
        }
    }

    /// Creates a scrollable, 2D array of widgets with tiles that each have a maximum cross-axis
    /// extent.
    ///
    /// Uses a [`SliverGridDelegateWithMaxCrossAxisExtent`] as the
    /// [`grid_delegate`](Self::grid_delegate).
    ///
    /// See also:
    ///
    ///  * [`SliverGrid::extent`], the equivalent constructor for [`SliverGrid`].
    pub fn extent(max_cross_axis_extent: f64) -> GridViewExtent {
        let grid_delegate = SliverGridDelegateWithMaxCrossAxisExtent::new(max_cross_axis_extent);
        GridViewExtent {
            grid_view: GridView::new(Rc::new(grid_delegate.clone())),
            grid_delegate,
        }
    }

    crate::scroll_view_setters!(GridView);

    /// Dart `GridView(padding:)`.
    pub fn padding(mut self, padding: EdgeInsetsGeometry) -> GridView {
        self.box_scroll_view.padding = Some(padding);
        self
    }

    list_arguments_setters!(GridView);
}

impl ScrollView for GridView {
    crate::scroll_view_accessors!();

    fn build_slivers(&self, app: &mut App, context: BuildContext) -> Vec<WidgetRef> {
        BoxScrollViewBase::build_slivers(self, app, context)
    }
}

impl BoxScrollView for GridView {
    crate::box_scroll_view_accessors!();

    fn build_child_layout(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
        SliverGrid::new(
            self.children_delegate.clone(),
            Rc::clone(&self.grid_delegate),
        )
        .into_widget()
    }
}

impl StatelessWidget for GridView {
    fn key(&self) -> Option<&KeyRef> {
        self.scroll_view.key.as_ref()
    }

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        ScrollViewBase::build(self, app, context)
    }
}

impl Clone for GridView {
    fn clone(&self) -> GridView {
        GridView {
            scroll_view: self.scroll_view.clone(),
            box_scroll_view: self.box_scroll_view.clone(),
            grid_delegate: Rc::clone(&self.grid_delegate),
            children_delegate: self.children_delegate.clone(),
            list_arguments: self.list_arguments.clone(),
        }
    }
}

impl Debug for GridView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("GridView")
            .field("gridDelegate", &self.grid_delegate)
            .field("childrenDelegate", &self.children_delegate)
            .finish_non_exhaustive()
    }
}

/// Dart's `GridView.builder(..)` arguments; the value converts to the [`GridView`].
pub struct GridViewBuilder {
    grid_view: GridView,
    delegate: SliverChildBuilderDelegate,
}

impl GridViewBuilder {
    fn new(
        grid_delegate: Rc<dyn SliverGridDelegate>,
        item_builder: NullableIndexedWidgetBuilder,
    ) -> GridViewBuilder {
        GridViewBuilder {
            grid_view: GridView::custom(
                grid_delegate,
                SliverChildListDelegate::new(Vec::new()).into_delegate(),
            ),
            delegate: SliverChildBuilderDelegate::from_builder(item_builder),
        }
    }

    /// Dart `itemCount:`, which also fills in [`ScrollViewData::semantic_child_count`], as
    /// Dart's `semanticChildCount ?? itemCount` does.
    pub fn item_count(mut self, item_count: i32) -> GridViewBuilder {
        self.delegate = self.delegate.child_count(item_count);
        if self.grid_view.scroll_view.semantic_child_count.is_none() {
            self.grid_view.scroll_view.semantic_child_count = Some(item_count);
        }
        self
    }

    /// Dart `findChildIndexCallback:`.
    pub fn find_child_index_callback(
        mut self,
        find_child_index_callback: ChildIndexGetter,
    ) -> GridViewBuilder {
        self.delegate = self
            .delegate
            .find_child_index_callback(find_child_index_callback);
        self
    }

    /// Dart `addAutomaticKeepAlives:`.
    pub fn add_automatic_keep_alives(mut self, value: bool) -> GridViewBuilder {
        self.delegate = self.delegate.add_automatic_keep_alives(value);
        self
    }

    /// Dart `addRepaintBoundaries:`.
    pub fn add_repaint_boundaries(mut self, value: bool) -> GridViewBuilder {
        self.delegate = self.delegate.add_repaint_boundaries(value);
        self
    }

    /// Dart `addSemanticIndexes:`.
    pub fn add_semantic_indexes(mut self, value: bool) -> GridViewBuilder {
        self.delegate = self.delegate.add_semantic_indexes(value);
        self
    }

    /// The [`GridView`] this builder describes.
    pub fn build(self) -> GridView {
        GridView {
            children_delegate: self.delegate.into_delegate(),
            ..self.grid_view
        }
    }
}

impl IntoWidget<StatelessKind> for GridViewBuilder {
    fn into_widget(self) -> WidgetRef {
        self.build().into_widget()
    }
}

/// The fluent arguments `GridView::count` and `GridView::extent` share: their grid delegate's
/// spacing, aspect ratio and tile extent, and the children.
macro_rules! tiles_constructor_setters {
    ($name:ident) => {
        /// Dart `mainAxisSpacing:`.
        pub fn main_axis_spacing(mut self, value: f64) -> $name {
            self.grid_delegate = self.grid_delegate.main_axis_spacing(value);
            self
        }

        /// Dart `crossAxisSpacing:`.
        pub fn cross_axis_spacing(mut self, value: f64) -> $name {
            self.grid_delegate = self.grid_delegate.cross_axis_spacing(value);
            self
        }

        /// Dart `childAspectRatio:`.
        pub fn child_aspect_ratio(mut self, value: f64) -> $name {
            self.grid_delegate = self.grid_delegate.child_aspect_ratio(value);
            self
        }

        /// Dart `mainAxisExtent:`.
        pub fn main_axis_extent(mut self, value: f64) -> $name {
            self.grid_delegate = self.grid_delegate.main_axis_extent(value);
            self
        }

        /// See [`GridView::children`].
        pub fn children(mut self, children: impl IntoIterator<Item = WidgetRef>) -> $name {
            self.grid_view = self.grid_view.children(children);
            self
        }

        /// See [`GridView::add_automatic_keep_alives`].
        pub fn add_automatic_keep_alives(mut self, value: bool) -> $name {
            self.grid_view = self.grid_view.add_automatic_keep_alives(value);
            self
        }

        /// See [`GridView::add_repaint_boundaries`].
        pub fn add_repaint_boundaries(mut self, value: bool) -> $name {
            self.grid_view = self.grid_view.add_repaint_boundaries(value);
            self
        }

        /// See [`GridView::add_semantic_indexes`].
        pub fn add_semantic_indexes(mut self, value: bool) -> $name {
            self.grid_view = self.grid_view.add_semantic_indexes(value);
            self
        }

        /// The [`GridView`] this value describes.
        pub fn build(self) -> GridView {
            GridView {
                grid_delegate: Rc::new(self.grid_delegate),
                ..self.grid_view
            }
        }
    };
}

/// Dart's `GridView.count(..)` arguments; the value converts to the [`GridView`].
pub struct GridViewCount {
    grid_view: GridView,
    grid_delegate: SliverGridDelegateWithFixedCrossAxisCount,
}

impl GridViewCount {
    tiles_constructor_setters!(GridViewCount);
}

impl IntoWidget<StatelessKind> for GridViewCount {
    fn into_widget(self) -> WidgetRef {
        self.build().into_widget()
    }
}

/// Dart's `GridView.extent(..)` arguments; the value converts to the [`GridView`].
pub struct GridViewExtent {
    grid_view: GridView,
    grid_delegate: SliverGridDelegateWithMaxCrossAxisExtent,
}

impl GridViewExtent {
    tiles_constructor_setters!(GridViewExtent);
}

impl IntoWidget<StatelessKind> for GridViewExtent {
    fn into_widget(self) -> WidgetRef {
        self.build().into_widget()
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use waft_foundation::AppCell;

    use waft_embedder::{Size, TextDirection};
    use waft_painting::EdgeInsets;
    use waft_rendering::{AnyRenderObject, RenderSliverPadding};

    use super::*;
    use crate::test_harness::{Harness, VIEW_HEIGHT, binding_cell, binding_mount, binding_pump};
    use crate::widgets::basic::{Directionality, SizedBox};
    use crate::widgets::media_query::MediaQueryData;
    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};

    const ITEM_EXTENT: f64 = 50.0;
    const ITEM_COUNT: usize = 40;

    /// The tree every scroll view test mounts: a text direction and a media query, which a
    /// `Scrollable` reads for its gesture settings.
    fn wrap<K>(child: impl IntoWidget<K>) -> WidgetRef {
        wrap_with(
            MediaQueryData::new().size(Size::new(300.0, VIEW_HEIGHT)),
            child,
        )
    }

    fn wrap_with<K>(data: MediaQueryData, child: impl IntoWidget<K>) -> WidgetRef {
        let query: WidgetRef = MediaQuery::new(data, child).into_widget();
        Directionality::new(TextDirection::Ltr, query).into_widget()
    }

    fn boxes(count: usize) -> Vec<WidgetRef> {
        (0..count)
            .map(|_| SizedBox::new().height(ITEM_EXTENT).into_widget())
            .collect()
    }

    /// Counts the render objects under `object` for which `matches` holds.
    fn count_render_objects(
        app: &App,
        object: AnyRenderObject,
        matches: &dyn Fn(&App, AnyRenderObject) -> bool,
    ) -> usize {
        let mut total = usize::from(matches(app, object));
        object.visit_children(app, &mut |child| {
            total += count_render_objects(app, child, matches);
        });
        total
    }

    fn item_count(app: &App, harness: &Harness) -> usize {
        count_render_objects(app, harness.render_root(app).as_object(), &|app, object| {
            object
                .as_box()
                .is_some_and(|render_box| render_box.size(app).height() == ITEM_EXTENT)
        })
    }

    #[test]
    fn a_list_view_lays_out_only_the_visible_children_and_scrolls_through_its_controller() {
        let cell = binding_cell();
        let mut app = cell.borrow_mut();
        let controller = ScrollController::default(&mut app);
        let list = ListView::new()
            .controller(controller.as_controller())
            .children(boxes(ITEM_COUNT));
        drop(app);
        binding_mount(&cell, wrap(list));
        let mut app = cell.borrow_mut();

        let visible = (VIEW_HEIGHT / ITEM_EXTENT) as usize;
        let laid_out = item_count_under_view(&mut app);
        assert!(
            laid_out >= visible && laid_out < ITEM_COUNT,
            "only the visible children (plus the cache) are laid out, not all of them: {laid_out}"
        );

        controller.jump_to(&mut app, 500.0);
        binding_pump(&mut app, std::time::Duration::ZERO);
        assert_eq!(controller.offset(&app), 500.0);
        let scrolled = item_count_under_view(&mut app);
        assert!(
            scrolled >= visible && scrolled < ITEM_COUNT,
            "still only the visible children (plus the cache) after scrolling: {scrolled}"
        );
    }

    fn item_count_under_view(app: &mut App) -> usize {
        let root = crate::binding::WidgetsBinding::instance(app)
            .root_element(app)
            .expect("a mounted root element")
            .find_render_object(app)
            .expect("a mounted view has a render object");
        count_render_objects(app, root, &|app, object| {
            object.as_box().is_some_and(|render_box| {
                render_box.has_size(app) && render_box.size(app).height() == ITEM_EXTENT
            })
        })
    }

    #[test]
    fn a_list_view_builder_creates_its_children_lazily() {
        let built: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
        let recorded = built.clone();
        let list = ListView::builder(move |_app, _context, index| {
            recorded.borrow_mut().push(index);
            Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
        })
        .item_count(1000)
        .build();

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(&mut app, wrap(list));
        harness.pump(&mut app);

        let built = built.borrow();
        assert!(!built.is_empty(), "the visible children are built");
        assert!(
            built.len() < 1000,
            "only the visible children are built, not all 1000: {}",
            built.len()
        );
        assert!(
            built.iter().all(|index| *index < built.len() as i32),
            "the builder is called for the leading indices only: {built:?}"
        );
    }

    #[test]
    fn a_list_view_separated_interleaves_items_and_separators() {
        let calls: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(Vec::new()));
        let items = calls.clone();
        let separators = calls.clone();
        let list = ListView::separated(
            move |_app, _context, index| {
                items.borrow_mut().push(format!("item {index}"));
                Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
            },
            move |_app, _context, index| {
                separators.borrow_mut().push(format!("separator {index}"));
                Some(SizedBox::new().height(ITEM_EXTENT).into_widget())
            },
            10,
        )
        .build();
        assert_eq!(list.scroll_view.semantic_child_count, Some(10));

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(&mut app, wrap(list));
        harness.pump(&mut app);

        let calls = calls.borrow();
        assert_eq!(calls[0], "item 0");
        assert_eq!(calls[1], "separator 0");
        assert_eq!(calls[2], "item 1");
        assert_eq!(calls[3], "separator 1");
    }

    #[test]
    fn a_custom_scroll_view_lays_out_a_box_adapter_above_a_sliver_list() {
        use crate::widgets::basic::SliverToBoxAdapter;

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let view = CustomScrollView::new().slivers([
            SliverToBoxAdapter::new()
                .child(SizedBox::new().height(120.0))
                .into_widget(),
            SliverList::list(boxes(10)).into_widget(),
        ]);
        let harness = Harness::mount(&mut app, wrap(view));
        harness.pump(&mut app);

        let header = count_render_objects(
            &app,
            harness.render_root(&app).as_object(),
            &|app, object| {
                object
                    .as_box()
                    .is_some_and(|render_box| render_box.size(app).height() == 120.0)
            },
        );
        assert_eq!(header, 1, "the box adapter's child is laid out");
        assert!(
            item_count(&app, &harness) > 0,
            "the sliver list's children are laid out below it"
        );
    }

    /// `GridView.count` sizes its tiles to fill each row and lays out only the rows in view
    /// and in the cache.
    #[test]
    fn a_grid_view_count_lays_out_the_rows_in_view() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let grid = GridView::count(3)
            .main_axis_spacing(10.0)
            .add_repaint_boundaries(false)
            .children(boxes(30))
            .build();
        assert_eq!(grid.scroll_view.semantic_child_count, Some(30));
        let harness = Harness::mount(&mut app, wrap(grid));
        harness.pump(&mut app);

        // Tiles are 100 square in the 300 wide view, rows 110 apart: the 200 high view and its
        // 250 of cache reach into the fifth row.
        let tiles = count_render_objects(
            &app,
            harness.render_root(&app).as_object(),
            &|app, object| {
                object
                    .as_box()
                    .is_some_and(|render_box| render_box.size(app) == Size::new(100.0, 100.0))
            },
        );
        assert_eq!(tiles, 15);
    }

    #[test]
    fn a_grid_view_builder_creates_its_tiles_lazily() {
        let built: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new(Vec::new()));
        let recorded = built.clone();
        let tiles = SliverGridDelegateWithMaxCrossAxisExtent::new(150.0);
        let grid = GridView::builder(Rc::new(tiles), move |_app, _context, index| {
            recorded.borrow_mut().push(index);
            Some(SizedBox::new().into_widget())
        })
        .item_count(1000)
        .build();

        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let harness = Harness::mount(&mut app, wrap(grid));
        harness.pump(&mut app);

        // Two columns of 150 square tiles: rows up to 450 are built, view and cache.
        let mut built = built.borrow().clone();
        built.sort();
        assert_eq!(built, (0..6).collect::<Vec<i32>>());
    }

    #[test]
    fn a_box_scroll_view_consumes_the_media_query_padding_along_the_scroll_axis() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let padding = EdgeInsets::from_ltrb(8.0, 16.0, 24.0, 32.0);
        let list = ListView::new().children(boxes(10));
        let harness = Harness::mount(
            &mut app,
            wrap_with(
                MediaQueryData::new()
                    .size(Size::new(300.0, VIEW_HEIGHT))
                    .padding(padding),
                list,
            ),
        );
        harness.pump(&mut app);

        let sliver_padding = find_sliver_padding(&app, harness.render_root(&app).as_object())
            .expect("the list wraps its sliver in a SliverPadding");
        assert_eq!(
            sliver_padding.padding(&app).resolve(None),
            EdgeInsets::from_ltrb(0.0, 16.0, 0.0, 32.0),
            "the main axis padding is consumed by the SliverPadding"
        );
    }

    fn find_sliver_padding(
        app: &App,
        object: AnyRenderObject,
    ) -> Option<waft_rendering::RenderHandle<RenderSliverPadding>> {
        if let Some(padding) = object.downcast::<RenderSliverPadding>(app) {
            return Some(padding);
        }
        let mut found = None;
        object.visit_children(app, &mut |child| {
            if found.is_none() {
                found = find_sliver_padding(app, child);
            }
        });
        found
    }
}