waft-widgets 0.14.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
//! Flutter counterpart: `widgets/single_child_scroll_view.dart`.
//!
//! Semantics and diagnostics wait; see `PORTING.md`.

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

use waft_animation::Curve;
use waft_embedder::{Clip, Matrix4, Offset, Rect, Size};
use waft_foundation::{App, DiagnosticPropertiesBuilder, DiagnosticsProperty, Handle, Listener};
use waft_gestures::DragStartBehavior;
use waft_painting::{
    Axis, AxisDirection, EdgeInsetsGeometry, axis_direction_to_axis, transform_rect,
};
use waft_rendering::{
    AnyRenderAbstractViewport, AnyRenderBox, AnyRenderObject, AnyViewportOffset, BoxConstraints,
    BoxHitTestResult, ClipRectLayer, EmptyParentData, HitTestBehavior, LayerHandle,
    PaintingContext, PipelineOwner, RenderAbstractViewport, RenderBox, RenderBoxData, RenderHandle,
    RenderObject, RenderObjectData, RenderObjectWithChildData, RenderObjectWithChildMixin,
    RevealedOffset, ViewportOffsetRef, show_in_viewport,
};

use crate::framework::{
    AnyElement, BuildContext, Element, ElementData, IntoWidget, KeyRef, RenderObjectElement,
    RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget,
    SingleChildRenderObjectElementBase, SingleChildRenderObjectElementData,
    SingleChildRenderObjectWidget, Slot, StatelessWidget, WidgetRef, downcast_widget,
};
use crate::widgets::basic::{Padding, 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::notification_listener::NotificationListener;
use crate::widgets::primary_scroll_controller::PrimaryScrollController;
use crate::widgets::scroll_configuration::ScrollConfiguration;
use crate::widgets::scroll_controller::ScrollControllerRef;
use crate::widgets::scroll_notification::{ScrollUpdateNotification, ViewportElementMixin};
use crate::widgets::scroll_physics::ScrollPhysicsRef;
use crate::widgets::scroll_view::ScrollViewKeyboardDismissBehavior;
use crate::widgets::scrollable::{Scrollable, ViewportBuilder};

/// A box in which a single widget can be scrolled.
///
/// This widget is useful when you have a single box that will normally be
/// entirely visible, for example a clock face in a time picker, but you need to
/// make sure it can be scrolled if the container gets too small in one axis
/// (the scroll direction).
///
/// It is also useful if you need to shrink-wrap in both axes (the main
/// scrolling direction as well as the cross axis), as one might see in a dialog
/// or pop-up menu. In that case, you might pair the [`SingleChildScrollView`]
/// with a `ListBody` child.
///
/// When you have a list of children and do not require cross-axis
/// shrink-wrapping behavior, for example a scrolling list that is always the
/// width of the screen, consider [`ListView`](crate::ListView), which is vastly
/// more efficient than a [`SingleChildScrollView`] containing a `ListBody` or
/// `Column` with many children.
///
/// See also:
///
///  * [`ListView`](crate::ListView), which handles multiple children in a scrolling list.
///  * `Scrollable`, which handles arbitrary scrolling effects.
#[derive(Clone, Debug)]
pub struct SingleChildScrollView {
    pub key: Option<KeyRef>,

    /// The [`Axis`] along which the scroll view's offset increases.
    ///
    /// 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,

    /// The amount of space by which to inset the child.
    pub padding: Option<EdgeInsetsGeometry>,

    /// 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<ScrollControllerRef>,

    /// Whether this is the primary scroll view associated with the parent
    /// [`PrimaryScrollController`].
    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.
    pub physics: Option<ScrollPhysicsRef>,

    /// The widget that scrolls.
    pub child: Option<WidgetRef>,

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

    /// 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,

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

    /// How this scroll view will dismiss the keyboard automatically.
    ///
    /// If `None` then it falls back to the inherited
    /// [`ScrollBehavior::get_keyboard_dismiss_behavior`](crate::ScrollBehavior::get_keyboard_dismiss_behavior).
    pub keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
}

impl Default for SingleChildScrollView {
    fn default() -> SingleChildScrollView {
        SingleChildScrollView {
            key: None,
            scroll_direction: Axis::Vertical,
            reverse: false,
            padding: None,
            controller: None,
            primary: None,
            physics: None,
            child: None,
            drag_start_behavior: DragStartBehavior::Start,
            clip_behavior: Clip::HardEdge,
            hit_test_behavior: HitTestBehavior::Opaque,
            restoration_id: None,
            keyboard_dismiss_behavior: None,
        }
    }
}

impl SingleChildScrollView {
    /// Creates a box in which a single widget can be scrolled.
    pub fn new() -> SingleChildScrollView {
        SingleChildScrollView::default()
    }

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

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

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

    /// Dart `SingleChildScrollView(padding:)`.
    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> SingleChildScrollView {
        let padding = padding.into();
        self.padding = Some(padding);
        self
    }

    /// Dart `SingleChildScrollView(controller:)`.
    pub fn controller(mut self, controller: ScrollControllerRef) -> SingleChildScrollView {
        debug_assert!(
            !self.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.controller = Some(controller);
        self
    }

    /// Dart `SingleChildScrollView(primary:)`.
    pub fn primary(mut self, primary: bool) -> SingleChildScrollView {
        debug_assert!(
            !(self.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.primary = Some(primary);
        self
    }

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

    /// Dart `SingleChildScrollView(child:)`.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SingleChildScrollView {
        self.child = Some(child.into_widget());
        self
    }

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

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

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

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

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

    fn get_direction(&self, app: &mut App, context: BuildContext) -> AxisDirection {
        get_axis_direction_from_axis_reverse_and_directionality(
            app,
            context,
            self.scroll_direction,
            self.reverse,
        )
    }

    /// Dart's `contents`: the child, inset by [`padding`](Self::padding) when there is one.
    fn contents(&self) -> Option<WidgetRef> {
        let contents = self.child.clone();
        let Some(padding) = self.padding else {
            return contents;
        };
        let mut inset = Padding::new(padding);
        if let Some(child) = contents {
            inset = inset.child(child);
        }
        Some(inset.into_widget())
    }
}

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

    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
        let axis_direction = self.get_direction(app, context);
        let contents = self.contents();
        let effective_primary = self.primary.unwrap_or_else(|| {
            self.controller.is_none()
                && PrimaryScrollController::should_inherit(app, context, self.scroll_direction)
        });

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

        let clip_behavior = self.clip_behavior;
        let viewport_builder: ViewportBuilder = Rc::new(move |_app, _context, offset| {
            let mut viewport =
                SingleChildViewport::new(offset, clip_behavior).axis_direction(axis_direction);
            if let Some(contents) = contents.clone() {
                viewport = viewport.child(contents);
            }
            viewport.into_widget()
        });

        let mut scrollable = Scrollable::new(viewport_builder)
            .drag_start_behavior(self.drag_start_behavior)
            .axis_direction(axis_direction)
            .clip_behavior(self.clip_behavior)
            .hit_test_behavior(self.hit_test_behavior);
        let has_scroll_controller = scroll_controller.is_some();
        if let Some(controller) = scroll_controller {
            scrollable = scrollable.controller(controller);
        }
        if let Some(physics) = self.physics.clone() {
            scrollable = scrollable.physics(physics);
        }
        if let Some(restoration_id) = self.restoration_id.clone() {
            scrollable = scrollable.restoration_id(restoration_id);
        }
        let mut scrollable = scrollable.into_widget();

        let effective_keyboard_dismiss_behavior =
            self.keyboard_dismiss_behavior.unwrap_or_else(|| {
                ScrollConfiguration::of(app, context).get_keyboard_dismiss_behavior(app, context)
            });

        if effective_keyboard_dismiss_behavior == ScrollViewKeyboardDismissBehavior::OnDrag {
            scrollable = NotificationListener::<ScrollUpdateNotification>::new(scrollable)
                .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();
        }

        if effective_primary && has_scroll_controller {
            // Further descendant scroll views will not inherit the same
            // `PrimaryScrollController`.
            PrimaryScrollController::none(scrollable).into_widget()
        } else {
            scrollable
        }
    }
}

/// Dart's `_SingleChildViewport`: the box viewport a [`SingleChildScrollView`] scrolls.
#[derive(Debug)]
pub struct SingleChildViewport {
    /// The direction in which the [`offset`](Self::offset)'s pixels increase.
    pub axis_direction: AxisDirection,
    /// Which part of the content inside the viewport should be visible.
    pub offset: ViewportOffsetRef,
    /// The content will be clipped (or not) according to this option.
    pub clip_behavior: Clip,
    /// The widget that scrolls.
    pub child: Option<WidgetRef>,
}

impl SingleChildViewport {
    /// Creates a viewport for a single box child.
    pub fn new(offset: ViewportOffsetRef, clip_behavior: Clip) -> SingleChildViewport {
        SingleChildViewport {
            axis_direction: AxisDirection::Down,
            offset,
            clip_behavior,
            child: None,
        }
    }

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

    /// Dart `_SingleChildViewport(child:)`.
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn child<K>(mut self, child: impl IntoWidget<K>) -> SingleChildViewport {
        self.child = Some(child.into_widget());
        self
    }
}

impl RenderObjectWidget for SingleChildViewport {
    type RenderObject = RenderSingleChildViewport;

    fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
        RenderSingleChildViewport::new(
            app,
            self.axis_direction,
            self.offset.clone(),
            None,
            self.clip_behavior,
        )
        .as_object()
    }

    fn update_render_object(
        &self,
        app: &mut App,
        _context: BuildContext,
        render_object: RenderHandle<RenderSingleChildViewport>,
    ) {
        // Order dependency: the offset setter reads the axis direction.
        render_object.set_axis_direction(app, self.axis_direction);
        render_object.set_offset(app, self.offset.clone());
        render_object.set_clip_behavior(app, self.clip_behavior);
    }
}

impl SingleChildRenderObjectWidget for SingleChildViewport {
    fn child(&self) -> Option<&WidgetRef> {
        self.child.as_ref()
    }

    fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
        SingleChildViewportElement::new(app, this).as_element()
    }
}

/// Dart's `_SingleChildViewportElement`: a single-child render object element that is also a
/// notification node, so a `ScrollNotification` bubbling past it counts one viewport deeper.
pub struct SingleChildViewportElement {
    element: ElementData,
    render_object_element: RenderObjectElementData,
    single_child: SingleChildRenderObjectElementData,
}

impl SingleChildViewportElement {
    /// Creates an element that uses the given widget as its configuration.
    pub fn new(app: &mut App, widget: WidgetRef) -> Handle<SingleChildViewportElement> {
        debug_assert!(downcast_widget::<SingleChildViewport>(&*widget).is_some());
        app.create(SingleChildViewportElement {
            element: ElementData::new(widget),
            render_object_element: RenderObjectElementData::default(),
            single_child: SingleChildRenderObjectElementData::default(),
        })
        .into_tree_node(app)
    }
}

impl RenderObjectElementWidget for SingleChildViewportElement {
    type Widget = SingleChildViewport;

    fn widget_of(widget: &WidgetRef) -> &SingleChildViewport {
        downcast_widget::<SingleChildViewport>(&**widget)
            .expect("a SingleChildViewportElement holds its SingleChildViewport")
    }
}

impl RenderObjectElement for SingleChildViewportElement {
    fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
        &app.get(self).render_object_element
    }

    fn render_object_element_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectElementData {
        &mut app.get_mut(self).render_object_element
    }
}

impl SingleChildRenderObjectElementBase for SingleChildViewportElement {
    fn single_child_data(self: Handle<Self>, app: &App) -> &SingleChildRenderObjectElementData {
        &app.get(self).single_child
    }

    fn single_child_data_mut(
        self: Handle<Self>,
        app: &mut App,
    ) -> &mut SingleChildRenderObjectElementData {
        &mut app.get_mut(self).single_child
    }
}

impl ViewportElementMixin for SingleChildViewportElement {}

impl Element for SingleChildViewportElement {
    crate::element_accessors!();

    const IS_RENDER_OBJECT_ELEMENT: bool = true;

    fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
        self.render_object_element_data(app).render_object()
    }

    fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
        None
    }

    fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
        self.render_object_element_data(app).debug_doing_build()
    }

    fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
        SingleChildRenderObjectElementBase::visit_children(self, app, visitor);
    }

    fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
        SingleChildRenderObjectElementBase::forget_child(self, app, child);
    }

    fn mount(
        self: Handle<Self>,
        app: &mut App,
        parent: Option<AnyElement>,
        new_slot: Option<Slot>,
    ) {
        SingleChildRenderObjectElementBase::mount(self, app, parent, new_slot);
    }

    fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
        SingleChildRenderObjectElementBase::update(self, app, new_widget);
    }

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

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

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

    fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
        RenderObjectElement::update_parent_data(self, app, parent_data_element);
    }

    fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::update_slot(self, app, new_slot);
    }

    fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
        RenderObjectElement::attach_render_object(self, app, new_slot);
    }

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

    fn insert_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        SingleChildRenderObjectElementBase::insert_render_object_child(self, app, child, slot);
    }

    fn move_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        old_slot: Option<Slot>,
        new_slot: Option<Slot>,
    ) {
        SingleChildRenderObjectElementBase::move_render_object_child(
            self, app, child, old_slot, new_slot,
        );
    }

    fn remove_render_object_child(
        self: Handle<Self>,
        app: &mut App,
        child: AnyRenderObject,
        slot: Option<Slot>,
    ) {
        SingleChildRenderObjectElementBase::remove_render_object_child(self, app, child, slot);
    }

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

    fn on_notification(
        self: Handle<Self>,
        app: &mut App,
        notification: &dyn crate::framework::Notification,
    ) -> bool {
        ViewportElementMixin::on_notification(self, app, notification)
    }
}

/// Dart's `_RenderSingleChildViewport`: a viewport that shows one box child, moved by a
/// `ViewportOffset` and sized to that child in the cross axis.
pub struct RenderSingleChildViewport {
    render_object: RenderObjectData,
    render_box: RenderBoxData,
    child: RenderObjectWithChildData<AnyRenderBox>,
    axis_direction: AxisDirection,
    offset: ViewportOffsetRef,
    clip_behavior: Clip,
    clip_rect_layer: LayerHandle<Handle<ClipRectLayer>>,
}

impl RenderSingleChildViewport {
    /// Creates a viewport for a single box child.
    pub fn new(
        app: &mut App,
        axis_direction: AxisDirection,
        offset: ViewportOffsetRef,
        child: Option<AnyRenderBox>,
        clip_behavior: Clip,
    ) -> RenderHandle<RenderSingleChildViewport> {
        let this = RenderHandle::new_box(
            app,
            RenderSingleChildViewport {
                render_object: RenderObjectData::new(),
                render_box: RenderBoxData::new(),
                child: RenderObjectWithChildData::new(),
                axis_direction,
                offset,
                clip_behavior,
                clip_rect_layer: LayerHandle::new(),
            },
        );
        this.set_child(app, child);
        this
    }

    /// The direction in which the [`offset`](Self::offset)'s pixels increase.
    pub fn axis_direction(self: RenderHandle<Self>, app: &App) -> AxisDirection {
        self.get(app).axis_direction
    }

    /// Sets [`axis_direction`](Self::axis_direction).
    pub fn set_axis_direction(self: RenderHandle<Self>, app: &mut App, value: AxisDirection) {
        if value == self.get(app).axis_direction {
            return;
        }
        self.get_mut(app).axis_direction = value;
        self.mark_needs_layout(app);
    }

    /// The axis along which the viewport scrolls.
    pub fn axis(self: RenderHandle<Self>, app: &App) -> Axis {
        axis_direction_to_axis(self.axis_direction(app))
    }

    /// Which part of the content inside the viewport should be visible.
    pub fn offset(self: RenderHandle<Self>, app: &App) -> AnyViewportOffset {
        self.get(app).offset.handle()
    }

    /// Sets [`offset`](Self::offset).
    pub fn set_offset(self: RenderHandle<Self>, app: &mut App, value: ViewportOffsetRef) {
        let old = self.offset(app);
        if value == old {
            return;
        }
        if self.attached(app) {
            old.remove_listener(app, &self.has_scrolled_listener());
        }
        let new = value.handle();
        // The old offset goes when this local does, after the listener moved off it.
        let _old = std::mem::replace(&mut self.get_mut(app).offset, value);
        if self.attached(app) {
            new.add_listener(app, self.has_scrolled_listener());
        }
        self.mark_needs_layout(app);
    }

    /// The content will be clipped (or not) according to this option.
    ///
    /// Defaults to [`Clip::None`].
    pub fn clip_behavior(self: RenderHandle<Self>, app: &App) -> Clip {
        self.get(app).clip_behavior
    }

    /// Sets [`clip_behavior`](Self::clip_behavior).
    pub fn set_clip_behavior(self: RenderHandle<Self>, app: &mut App, value: Clip) {
        if value == self.get(app).clip_behavior {
            return;
        }
        self.get_mut(app).clip_behavior = value;
        self.mark_needs_paint(app);
    }

    /// Dart's `_offset.addListener(_hasScrolled)` tear-off.
    fn has_scrolled_listener(self: RenderHandle<Self>) -> Listener {
        Listener::handle_method(self.handle(), has_scrolled)
    }

    fn viewport_extent(self: RenderHandle<Self>, app: &App) -> f64 {
        debug_assert!(self.has_size(app));
        match self.axis(app) {
            Axis::Horizontal => self.size(app).width(),
            Axis::Vertical => self.size(app).height(),
        }
    }

    fn min_scroll_extent(self: RenderHandle<Self>, app: &App) -> f64 {
        debug_assert!(self.has_size(app));
        0.0
    }

    fn max_scroll_extent(self: RenderHandle<Self>, app: &App) -> f64 {
        debug_assert!(self.has_size(app));
        let Some(child) = self.child(app) else {
            return 0.0;
        };
        let extent = match self.axis(app) {
            Axis::Horizontal => child.size(app).width() - self.size(app).width(),
            Axis::Vertical => child.size(app).height() - self.size(app).height(),
        };
        extent.max(0.0)
    }

    fn get_inner_constraints(
        self: RenderHandle<Self>,
        app: &App,
        constraints: BoxConstraints,
    ) -> BoxConstraints {
        match self.axis(app) {
            Axis::Horizontal => constraints.height_constraints(),
            Axis::Vertical => constraints.width_constraints(),
        }
    }

    /// The offset the child is painted at, for the offset's current pixels.
    fn paint_offset(self: RenderHandle<Self>, app: &App) -> Offset {
        self.paint_offset_for_position(app, self.offset(app).pixels(app))
    }

    fn paint_offset_for_position(self: RenderHandle<Self>, app: &App, position: f64) -> Offset {
        let child = self.child(app).expect("a paint offset needs the content");
        let child_size = child.size(app);
        let size = self.size(app);
        match self.axis_direction(app) {
            AxisDirection::Up => Offset::new(0.0, position - child_size.height() + size.height()),
            AxisDirection::Left => Offset::new(position - child_size.width() + size.width(), 0.0),
            AxisDirection::Right => Offset::new(-position, 0.0),
            AxisDirection::Down => Offset::new(0.0, -position),
        }
    }

    fn should_clip_at_paint_offset(
        self: RenderHandle<Self>,
        app: &App,
        paint_offset: Offset,
    ) -> bool {
        let child = self.child(app).expect("the clip test needs the content");
        match self.clip_behavior(app) {
            Clip::None => false,
            Clip::HardEdge | Clip::AntiAlias | Clip::AntiAliasWithSaveLayer => {
                let child_size = child.size(app);
                let size = self.size(app);
                paint_offset.dx() < 0.0
                    || paint_offset.dy() < 0.0
                    || paint_offset.dx() + child_size.width() > size.width()
                    || paint_offset.dy() + child_size.height() > size.height()
            }
        }
    }

    fn paint_contents(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        let child = self.child(app).expect("checked by the caller");
        let paint_offset = self.paint_offset(app);
        context.paint_child(app, child.as_object(), offset + paint_offset);
    }
}

/// Dart's `_hasScrolled`: a named function so that the listener added on attach compares equal
/// to the one removed on detach.
fn has_scrolled(this: Handle<RenderSingleChildViewport>, app: &mut App) {
    RenderHandle::from_handle(this).mark_needs_paint(app);
}

/// Dart's `transform.translateByDouble(dx, dy, 0, 1)`.
fn translate(transform: &mut Matrix4, offset: Offset) {
    *transform = transform.then(&Matrix4::translation(
        offset.dx() as f32,
        offset.dy() as f32,
    ));
}

impl RenderObjectWithChildMixin for RenderSingleChildViewport {
    type ChildType = AnyRenderBox;

    fn child_data(self: RenderHandle<Self>, app: &App) -> &RenderObjectWithChildData<AnyRenderBox> {
        &self.get(app).child
    }

    fn child_data_mut(
        self: RenderHandle<Self>,
        app: &mut App,
    ) -> &mut RenderObjectWithChildData<AnyRenderBox> {
        &mut self.get_mut(app).child
    }
}

impl RenderObject for RenderSingleChildViewport {
    waft_rendering::render_object_accessors!();

    fn is_repaint_boundary(self: RenderHandle<Self>, _app: &App) -> bool {
        true
    }

    fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
        if let Some(child) = self.child(app) {
            child.as_object().attach(app, owner);
        }
        self.offset(app)
            .add_listener(app, self.has_scrolled_listener());
    }

    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
        self.offset(app)
            .remove_listener(app, &self.has_scrolled_listener());
        if let Some(child) = self.child(app) {
            child.as_object().detach(app);
        }
    }

    fn visit_children(
        self: RenderHandle<Self>,
        app: &App,
        visitor: &mut dyn FnMut(AnyRenderObject),
    ) {
        if let Some(child) = self.child(app) {
            visitor(child.as_object());
        }
    }

    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
        let constraints = self.constraints(app);
        match self.child(app) {
            None => self.set_size(app, constraints.smallest()),
            Some(child) => {
                let inner_constraints = self.get_inner_constraints(app, constraints);
                child.layout(app, inner_constraints, true);
                let size = constraints.constrain(child.size(app));
                self.set_size(app, size);
            }
        }

        let offset = self.offset(app);
        if offset.has_pixels(app) {
            let pixels = offset.pixels(app);
            let max_scroll_extent = self.max_scroll_extent(app);
            let min_scroll_extent = self.min_scroll_extent(app);
            if pixels > max_scroll_extent {
                offset.correct_by(app, max_scroll_extent - pixels);
            } else if pixels < min_scroll_extent {
                offset.correct_by(app, min_scroll_extent - pixels);
            }
        }

        let viewport_extent = self.viewport_extent(app);
        offset.apply_viewport_dimension(app, viewport_extent);
        let (min_scroll_extent, max_scroll_extent) =
            (self.min_scroll_extent(app), self.max_scroll_extent(app));
        offset.apply_content_dimensions(app, min_scroll_extent, max_scroll_extent);
    }

    fn paint(
        self: RenderHandle<Self>,
        app: &mut App,
        context: &mut PaintingContext,
        offset: Offset,
    ) {
        if self.child(app).is_none() {
            return;
        }
        let paint_offset = self.paint_offset(app);
        if self.should_clip_at_paint_offset(app, paint_offset) {
            let bounds = Offset::ZERO & self.size(app);
            let clip_behavior = self.clip_behavior(app);
            let old = self.get(app).clip_rect_layer.layer();
            let layer = context.push_clip_rect(
                app,
                self.as_object().needs_compositing(app),
                offset,
                bounds,
                |app, context, offset| self.paint_contents(app, context, offset),
                clip_behavior,
                old,
            );
            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, layer);
        } else {
            LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
            self.paint_contents(app, context, offset);
        }
    }

    fn dispose(self: RenderHandle<Self>, app: &mut App) {
        LayerHandle::set_layer(app, |app| &mut self.get_mut(app).clip_rect_layer, None);
        waft_rendering::RenderObjectBase::dispose(self, app);
    }

    /// Dart's `describeApproximatePaintClip`: the content is clipped to the viewport when the
    /// paint offset takes it past an edge.
    fn describe_approximate_paint_clip(
        self: RenderHandle<Self>,
        app: &App,
        _child: AnyRenderObject,
    ) -> Option<Rect> {
        // Dart's `child != null` is the erased child the caller visits.
        if self.child(app).is_some()
            && self.should_clip_at_paint_offset(app, self.paint_offset(app))
        {
            Some(Offset::ZERO & self.size(app))
        } else {
            None
        }
    }

    fn show_on_screen(
        self: RenderHandle<Self>,
        app: &mut App,
        descendant: Option<AnyRenderObject>,
        rect: Option<Rect>,
        duration: Duration,
        curve: Rc<dyn Curve>,
    ) {
        let offset = self.offset(app);
        if !offset.allow_implicit_scrolling(app) {
            return waft_rendering::RenderObjectBase::show_on_screen(
                self, app, descendant, rect, duration, curve,
            );
        }

        let new_rect = show_in_viewport(
            app,
            descendant,
            rect,
            self.as_abstract_viewport(),
            offset,
            duration,
            Rc::clone(&curve),
        );
        waft_rendering::RenderObjectBase::show_on_screen(
            self, app, None, new_rect, duration, curve,
        );
    }

    fn debug_fill_properties(
        self: RenderHandle<Self>,
        app: &App,
        properties: &mut DiagnosticPropertiesBuilder,
    ) {
        properties.add(DiagnosticsProperty::<Offset>::new(
            "offset",
            Some(self.paint_offset(app)),
        ));
    }

    fn interface(self: RenderHandle<Self>, id: TypeId) -> Option<Box<dyn Any>> {
        (id == TypeId::of::<AnyRenderAbstractViewport>())
            .then(|| Box::new(self.as_abstract_viewport()) as Box<dyn Any>)
    }
}

impl RenderBox for RenderSingleChildViewport {
    waft_rendering::render_box_accessors!();

    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
        // We don't actually use the offset argument in `BoxParentData`, so let's avoid
        // allocating it at all.
        if child.parent_data(app).is_none() {
            child.set_parent_data(app, EmptyParentData);
        }
    }

    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
        match self.child(app) {
            Some(child) => child.get_min_intrinsic_width(app, height),
            None => 0.0,
        }
    }

    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
        match self.child(app) {
            Some(child) => child.get_max_intrinsic_width(app, height),
            None => 0.0,
        }
    }

    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
        match self.child(app) {
            Some(child) => child.get_min_intrinsic_height(app, width),
            None => 0.0,
        }
    }

    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
        match self.child(app) {
            Some(child) => child.get_max_intrinsic_height(app, width),
            None => 0.0,
        }
    }

    // We don't override `compute_distance_to_actual_baseline`, because we want the default
    // behavior (returning none). Otherwise, as you scroll, it would shift in its parent if the
    // parent was baseline-aligned, which makes no sense.

    fn compute_dry_layout(
        self: RenderHandle<Self>,
        app: &mut App,
        constraints: BoxConstraints,
    ) -> Size {
        let Some(child) = self.child(app) else {
            return constraints.smallest();
        };
        let inner_constraints = self.get_inner_constraints(app, constraints);
        let child_size = child.get_dry_layout(app, inner_constraints);
        constraints.constrain(child_size)
    }

    fn apply_paint_transform(
        self: RenderHandle<Self>,
        app: &App,
        _child: AnyRenderObject,
        transform: &mut Matrix4,
    ) {
        translate(transform, self.paint_offset(app));
    }

    fn hit_test_children(
        self: RenderHandle<Self>,
        app: &mut App,
        result: &mut BoxHitTestResult<'_>,
        position: Offset,
    ) -> bool {
        let Some(child) = self.child(app) else {
            return false;
        };
        let paint_offset = self.paint_offset(app);
        result.add_with_paint_offset(Some(paint_offset), position, |result, transformed| {
            debug_assert_eq!(transformed, position + -paint_offset);
            child.hit_test(app, result, transformed)
        })
    }
}

impl RenderAbstractViewport for RenderSingleChildViewport {
    fn get_offset_to_reveal(
        self: RenderHandle<Self>,
        app: &App,
        target: AnyRenderObject,
        alignment: f64,
        rect: Option<Rect>,
        _axis: Option<Axis>,
    ) -> RevealedOffset {
        let rect = rect.unwrap_or_else(|| target.paint_bounds(app));
        let Some(target_box) = target.as_box() else {
            return RevealedOffset::new(self.offset(app).pixels(app), rect);
        };

        let child = self.child(app).expect("the content is revealed in");
        let transform = target_box
            .as_object()
            .get_transform_to(app, Some(child.as_object()));
        let bounds = transform_rect(&transform, rect);
        let content_size = child.size(app);
        let size = self.size(app);

        let (main_axis_extent, leading_scroll_offset, target_main_axis_extent) =
            match self.axis_direction(app) {
                AxisDirection::Up => (
                    size.height(),
                    content_size.height() - bounds.bottom,
                    bounds.height(),
                ),
                AxisDirection::Left => (
                    size.width(),
                    content_size.width() - bounds.right,
                    bounds.width(),
                ),
                AxisDirection::Right => (size.width(), bounds.left, bounds.width()),
                AxisDirection::Down => (size.height(), bounds.top, bounds.height()),
            };

        let target_offset =
            leading_scroll_offset - (main_axis_extent - target_main_axis_extent) * alignment;
        let target_rect = bounds.shift(self.paint_offset_for_position(app, target_offset));
        RevealedOffset::new(target_offset, target_rect)
    }
}

#[cfg(test)]
mod tests {
    use std::any::Any;

    use waft_embedder::{SceneBuilder, Size, TextDirection, valo::Op};
    use waft_foundation::DiagnosticLevel;
    use waft_gestures::{HitTestEntry, HitTestResult};
    use waft_painting::{EdgeInsets, transform_point};
    use waft_rendering::{BoxHitTestEntry, RenderPadding};

    use super::*;
    use crate::testing::{WidgetTester, test_widgets};
    use crate::widgets::basic::{Directionality, Listener, SizedBox};
    use crate::widgets::media_query::{MediaQuery, MediaQueryData};
    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};

    const VIEW_WIDTH: f64 = WidgetTester::SIZE.width();
    const VIEW_HEIGHT: f64 = WidgetTester::SIZE.height();
    const CONTENT_WIDTH: f64 = 100.0;
    /// Longer than the view is wide and high.
    const CONTENT_HEIGHT: f64 = 1000.0;
    /// The height of the target inside the content, and the space above it, which puts the
    /// target below the view at scroll offset zero.
    const TARGET_EXTENT: f64 = 50.0;
    const LEADING_EXTENT: f64 = 700.0;

    /// The tree every 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 {
        let query: WidgetRef =
            MediaQuery::new(MediaQueryData::new().size(WidgetTester::SIZE), child).into_widget();
        Directionality::new(TextDirection::Ltr, query).into_widget()
    }

    /// A box that answers a hit test, so a hit can tell which child was reached.
    fn opaque(width: f64, height: f64) -> WidgetRef {
        Listener {
            behavior: HitTestBehavior::Opaque,
            child: Some(SizedBox::new().width(width).height(height).into_widget()),
            ..Default::default()
        }
        .into_widget()
    }

    /// Content taller than the viewport, with an opaque target `LEADING_EXTENT` down it.
    fn tall_content() -> WidgetRef {
        Padding::new(EdgeInsetsGeometry::Insets(EdgeInsets::only(
            0.0,
            LEADING_EXTENT,
            0.0,
            CONTENT_HEIGHT - LEADING_EXTENT - TARGET_EXTENT,
        )))
        .child(opaque(CONTENT_WIDTH, TARGET_EXTENT))
        .into_widget()
    }

    fn find<T: RenderObject>(app: &App, object: AnyRenderObject) -> Option<RenderHandle<T>> {
        if let Some(found) = object.downcast::<T>(app) {
            return Some(found);
        }
        let mut found = None;
        object.visit_children(app, &mut |child| {
            found = found.or_else(|| find::<T>(app, child));
        });
        found
    }

    fn mount(
        tester: &mut WidgetTester,
        view: SingleChildScrollView,
    ) -> RenderHandle<RenderSingleChildViewport> {
        tester.pump_widget(wrap(view));
        tester.first::<RenderSingleChildViewport>()
    }

    /// The offset the viewport paints its content at.
    fn content_offset(app: &App, viewport: RenderHandle<RenderSingleChildViewport>) -> Offset {
        let child = viewport.child(app).expect("the content");
        let mut transform = Matrix4::IDENTITY;
        viewport
            .as_object()
            .apply_paint_transform(app, child.as_object(), &mut transform);
        transform_point(&transform, Offset::ZERO)
    }

    /// The boxes a hit test at `position` walked, innermost first.
    fn hit_boxes(
        app: &mut App,
        viewport: RenderHandle<RenderSingleChildViewport>,
        position: Offset,
    ) -> Vec<AnyRenderBox> {
        let mut result = HitTestResult::new();
        viewport
            .as_box()
            .hit_test(app, &mut BoxHitTestResult::wrap(&mut result), position);
        result
            .path()
            .iter()
            .filter_map(|entry: &HitTestEntry| {
                let target: &dyn Any = entry.target();
                target
                    .downcast_ref::<BoxHitTestEntry>()
                    .map(BoxHitTestEntry::target)
            })
            .collect()
    }

    /// The valo ops the viewport's own layer records.
    fn scene_ops(app: &mut App, viewport: RenderHandle<RenderSingleChildViewport>) -> Vec<Op> {
        let scene = viewport
            .as_object()
            .debug_layer(app)
            .expect("painted")
            .build_scene(app, SceneBuilder::new());
        waft_embedder::flattened_ops(&waft_embedder::slices(&scene, |_| None).picture_with_room())
    }

    #[test]
    fn a_vertical_view_gives_its_child_unbounded_height_and_keeps_the_viewport_height() {
        test_widgets(|tester| {
            let controller = tester.update(ScrollController::default);
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .controller(controller.erase())
                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
            );
            let app = tester.cell.borrow();

            // The view's constraints are tight, as flutter_test's are, so the cross axis is
            // the view's width.
            let child = viewport.child(&app).expect("the content");
            assert_eq!(child.size(&app), Size::new(VIEW_WIDTH, CONTENT_HEIGHT));
            assert_eq!(viewport.size(&app), WidgetTester::SIZE);
            assert_eq!(
                controller.position(&app).max_scroll_extent(&app),
                CONTENT_HEIGHT - VIEW_HEIGHT
            );
        });
    }

    #[test]
    fn a_horizontal_view_gives_its_child_unbounded_width_and_keeps_the_viewport_width() {
        test_widgets(|tester| {
            let controller = tester.update(ScrollController::default);
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .scroll_direction(Axis::Horizontal)
                    .controller(controller.erase())
                    .child(SizedBox::new().width(CONTENT_HEIGHT).height(CONTENT_WIDTH)),
            );
            let app = tester.cell.borrow();

            // The view's constraints are tight, as flutter_test's are, so the cross axis is
            // the view's height.
            let child = viewport.child(&app).expect("the content");
            assert_eq!(child.size(&app), Size::new(CONTENT_HEIGHT, VIEW_HEIGHT));
            assert_eq!(viewport.size(&app), WidgetTester::SIZE);
            assert_eq!(
                controller.position(&app).max_scroll_extent(&app),
                CONTENT_HEIGHT - VIEW_WIDTH
            );
        });
    }

    #[test]
    fn the_content_offset_follows_the_controller() {
        test_widgets(|tester| {
            let controller = tester.update(ScrollController::default);
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .controller(controller.erase())
                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
            );
            assert_eq!(
                content_offset(&tester.cell.borrow(), viewport),
                Offset::ZERO
            );

            tester.update(|app| controller.jump_to(app, 120.0));
            tester.pump();
            assert_eq!(
                content_offset(&tester.cell.borrow(), viewport),
                Offset::new(0.0, -120.0)
            );
        });
    }

    /// `single_child_scroll_view.dart`'s `_RenderSingleChildViewport.debugFillProperties`: the
    /// offset the child is painted at.
    #[test]
    fn a_viewport_dump_shows_the_paint_offset() {
        test_widgets(|tester| {
            let controller = tester.update(ScrollController::default);
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .controller(controller.erase())
                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
            );
            tester.update(|app| controller.jump_to(app, 120.0));
            tester.pump();

            let dump = viewport
                .as_object()
                .to_string_deep_with(&tester.cell.borrow(), DiagnosticLevel::Info);
            assert!(dump.contains("offset: Offset(0.0, -120.0)"), "{dump}");
        });
    }

    #[test]
    fn a_reversed_view_starts_at_the_end_of_its_content() {
        test_widgets(|tester| {
            let controller = tester.update(ScrollController::default);
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .reverse(true)
                    .controller(controller.erase())
                    .child(SizedBox::new().width(CONTENT_WIDTH).height(CONTENT_HEIGHT)),
            );
            {
                let app = tester.cell.borrow();
                assert_eq!(viewport.axis_direction(&app), AxisDirection::Up);
                // At scroll offset zero the content's trailing edge sits on the viewport's.
                assert_eq!(
                    content_offset(&app, viewport),
                    Offset::new(0.0, VIEW_HEIGHT - CONTENT_HEIGHT)
                );
            }

            tester.update(|app| controller.jump_to(app, 120.0));
            tester.pump();
            assert_eq!(
                content_offset(&tester.cell.borrow(), viewport),
                Offset::new(0.0, VIEW_HEIGHT - CONTENT_HEIGHT + 120.0)
            );
        });
    }

    #[test]
    fn get_offset_to_reveal_answers_the_offset_that_brings_a_descendant_to_an_edge() {
        test_widgets(|tester| {
            let viewport = mount(tester, SingleChildScrollView::new().child(tall_content()));
            let app = tester.cell.borrow();
            let padding = find::<RenderPadding>(&app, viewport.as_object()).expect("the padding");
            let target = padding.child(&app).expect("the target").as_object();

            // The view's tight constraints make the target as wide as the view.
            let leading = viewport.get_offset_to_reveal(&app, target, 0.0, None, None);
            assert_eq!(leading.offset, LEADING_EXTENT);
            assert_eq!(
                leading.rect,
                Rect::from_ltwh(0.0, 0.0, VIEW_WIDTH, TARGET_EXTENT)
            );

            let trailing = viewport.get_offset_to_reveal(&app, target, 1.0, None, None);
            assert_eq!(
                trailing.offset,
                LEADING_EXTENT - (VIEW_HEIGHT - TARGET_EXTENT)
            );
            assert_eq!(
                trailing.rect,
                Rect::from_ltwh(0.0, VIEW_HEIGHT - TARGET_EXTENT, VIEW_WIDTH, TARGET_EXTENT)
            );
        });
    }

    #[test]
    fn a_hit_test_reaches_the_content_through_the_scroll_offset() {
        test_widgets(|tester| {
            let controller = tester.update(ScrollController::default);
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .controller(controller.erase())
                    .child(tall_content()),
            );
            let target = {
                let app = tester.cell.borrow();
                let padding =
                    find::<RenderPadding>(&app, viewport.as_object()).expect("the padding");
                padding.child(&app).expect("the target")
            };

            let near_the_top = Offset::new(50.0, 10.0);
            assert!(
                !tester
                    .update(|app| hit_boxes(app, viewport, near_the_top))
                    .contains(&target),
                "the target is scrolled out of view"
            );

            tester.update(|app| controller.jump_to(app, LEADING_EXTENT));
            tester.pump();
            assert!(
                tester
                    .update(|app| hit_boxes(app, viewport, near_the_top))
                    .contains(&target),
                "scrolling the target to the leading edge puts it under the pointer"
            );
        });
    }

    /// Content that paints, so a clip around it reaches the scene: valo drops a scope that
    /// draws nothing.
    fn painted(width: f64, height: f64) -> SizedBox {
        SizedBox::new()
            .width(width)
            .height(height)
            .child(crate::widgets::basic::ColoredBox::new(
                waft_embedder::Color::new(0xFF00FF00),
            ))
    }

    #[test]
    fn overflowing_content_is_clipped_unless_the_clip_behavior_says_otherwise() {
        test_widgets(|tester| {
            let viewport = mount(
                tester,
                SingleChildScrollView::new().child(painted(CONTENT_WIDTH, CONTENT_HEIGHT)),
            );
            let ops = tester.update(|app| scene_ops(app, viewport));
            assert!(
                ops.iter().any(|op| matches!(op, Op::ClipPath { .. })),
                "content taller than the viewport is clipped: {ops:?}"
            );
        });

        test_widgets(|tester| {
            let viewport = mount(
                tester,
                SingleChildScrollView::new()
                    .clip_behavior(Clip::None)
                    .child(painted(CONTENT_WIDTH, CONTENT_HEIGHT)),
            );
            assert!(
                !tester
                    .update(|app| scene_ops(app, viewport))
                    .iter()
                    .any(|op| matches!(op, Op::ClipPath { .. })),
                "Clip::None paints the content unclipped"
            );
        });

        test_widgets(|tester| {
            let viewport = mount(
                tester,
                SingleChildScrollView::new().child(painted(CONTENT_WIDTH, VIEW_HEIGHT)),
            );
            assert!(
                !tester
                    .update(|app| scene_ops(app, viewport))
                    .iter()
                    .any(|op| matches!(op, Op::ClipPath { .. })),
                "content that fits needs no clip"
            );
        });
    }

    /// `_RenderSingleChildViewport.describeApproximatePaintClip`: content that overflows is
    /// described as clipped to the viewport, and `Clip::None` or content that fits as not
    /// clipped.
    #[test]
    fn describe_approximate_paint_clip_answers_the_viewports_clip() {
        for (clip_behavior, content_height, clipped) in [
            (Clip::HardEdge, CONTENT_HEIGHT, true),
            (Clip::None, CONTENT_HEIGHT, false),
            (Clip::HardEdge, VIEW_HEIGHT, false),
        ] {
            test_widgets(|tester| {
                let viewport = mount(
                    tester,
                    SingleChildScrollView::new()
                        .clip_behavior(clip_behavior)
                        .child(painted(CONTENT_WIDTH, content_height)),
                );
                let app = tester.cell.borrow();
                let child = viewport.child(&app).expect("the content");
                let expected = clipped.then(|| Offset::ZERO & viewport.size(&app));
                assert_eq!(
                    viewport
                        .as_object()
                        .describe_approximate_paint_clip(&app, child.as_object()),
                    expected,
                    "{clip_behavior:?}, content {content_height}"
                );
            });
        }
    }
}