waft-widgets 0.9.1

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
//! Flutter counterpart: `widgets/scroll_configuration.dart`.

use std::any::{Any, TypeId};
use std::collections::HashSet;
use std::fmt::{self, Debug};
use std::ops::Deref;
use std::rc::Rc;

use waft_embedder::{Color, PointerDeviceKind, TargetPlatform};
use waft_foundation::App;
use waft_gestures::{
    GestureVelocityTrackerBuilder, IOSScrollViewFlingVelocityTracker,
    MacOSScrollViewFlingVelocityTracker, MultitouchDragStrategy, VelocityTracker,
};
use waft_services::LogicalKeyboardKey;

use crate::framework::{BuildContext, InheritedWidget, IntoWidget, KeyRef, WidgetRef};
use crate::widgets::overscroll_indicator::GlowingOverscrollIndicator;
use crate::widgets::scroll_physics::{
    BouncingScrollPhysics, ClampingScrollPhysics, RangeMaintainingScrollPhysics,
    ScrollDecelerationRate, ScrollPhysicsRef,
};
use crate::widgets::scroll_view::ScrollViewKeyboardDismissBehavior;
use crate::widgets::scrollable_helpers::ScrollableDetails;
use crate::widgets::scrollbar::RawScrollbar;

const K_DEFAULT_GLOW_COLOR: Color = Color::new(0xFFFFFFFF);

/// Device types that scrollables should accept drag gestures from by default.
///
/// Dart's `_kTouchLikeDeviceTypes`, a function because a `HashSet` has no `const`
/// constructor.
fn k_touch_like_device_types() -> HashSet<PointerDeviceKind> {
    HashSet::from([
        PointerDeviceKind::Touch,
        PointerDeviceKind::Stylus,
        PointerDeviceKind::InvertedStylus,
        PointerDeviceKind::Trackpad,
        // The VoiceAccess sends pointer events with unknown type when scrolling
        // scrollables.
        PointerDeviceKind::Unknown,
    ])
}

/// Types of overscroll indicators supported by [`TargetPlatform::Android`].
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AndroidOverscrollIndicator {
    /// Utilizes a `StretchingOverscrollIndicator`, which transforms the contents
    /// of a `ScrollView` when overscrolled.
    Stretch,

    /// Utilizes a `GlowingOverscrollIndicator`, painting a glowing semi circle on
    /// top of the `ScrollView` in response to overscrolling.
    Glow,
}

/// Describes how `Scrollable` widgets should behave.
///
/// Used by [`ScrollConfiguration`] to configure the `Scrollable` widgets in a
/// subtree.
///
/// This trait can be implemented to further customize a [`ScrollBehavior`] for a
/// subtree. For example, overriding [`get_scroll_physics`](Self::get_scroll_physics) sets the
/// default [`ScrollPhysics`](crate::ScrollPhysics) for `Scrollable`s that inherit this [`ScrollConfiguration`].
///
/// When looking to easily toggle the default decorations, use
/// [`ScrollBehaviorRef::copy_with`] instead of writing a new [`ScrollBehavior`].
/// The `scrollbars` and `overscroll` flags can turn these decorations off.
///
/// See also:
///
///   * [`ScrollConfiguration`], the inherited widget that controls how
///     `Scrollable` widgets behave in a subtree.
pub trait ScrollBehavior: Debug + 'static {
    /// The value behind the erased behavior, for Dart's `behavior.runtimeType` and the
    /// covariant `oldDelegate` a [`should_notify`](Self::should_notify) override casts.
    fn as_any(&self) -> &dyn Any;

    /// The platform whose scroll physics should be implemented.
    ///
    /// Defaults to the current platform.
    fn get_platform(&self, app: &mut App, context: BuildContext) -> TargetPlatform {
        ScrollBehaviorBase::get_platform(app, context)
    }

    /// The device kinds that the scrollable will accept drag gestures from.
    ///
    /// By default only [`PointerDeviceKind::Touch`], [`PointerDeviceKind::Stylus`],
    /// [`PointerDeviceKind::InvertedStylus`], and [`PointerDeviceKind::Trackpad`]
    /// are configured to create drag gestures. Enabling this for
    /// [`PointerDeviceKind::Mouse`] will make it difficult or impossible to select
    /// text in scrollable containers and is not recommended.
    fn drag_devices(&self) -> HashSet<PointerDeviceKind> {
        ScrollBehaviorBase::drag_devices()
    }

    /// The multi-finger drag strategy on multi-touch devices.
    ///
    /// By default, [`MultitouchDragStrategy::LatestPointer`] is configured to
    /// create drag gestures for non-Apple platforms, and
    /// [`MultitouchDragStrategy::AverageBoundaryPointers`] for Apple platforms.
    fn get_multitouch_drag_strategy(
        &self,
        app: &mut App,
        context: BuildContext,
    ) -> MultitouchDragStrategy {
        ScrollBehaviorBase::get_multitouch_drag_strategy(self, app, context)
    }

    /// A set of [`LogicalKeyboardKey`]s that, when any or all are pressed in
    /// combination with a [`PointerDeviceKind::Mouse`] pointer scroll event, will
    /// flip the axes of the scroll input.
    ///
    /// This will for example, result in the input of a vertical mouse wheel, to
    /// move the `ScrollPosition` of a `ScrollView` with an
    /// [`waft_painting::Axis::Horizontal`] scroll direction.
    ///
    /// If other keys exclusive of this set are pressed during a scroll event, in
    /// conjunction with keys from this set, the scroll input will still be
    /// flipped.
    ///
    /// Defaults to [`LogicalKeyboardKey::SHIFT_LEFT`] and
    /// [`LogicalKeyboardKey::SHIFT_RIGHT`].
    fn pointer_axis_modifiers(&self) -> HashSet<LogicalKeyboardKey> {
        ScrollBehaviorBase::pointer_axis_modifiers()
    }

    /// Applies a [`RawScrollbar`] to the child widget on desktop platforms.
    fn build_scrollbar(
        &self,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
        details: &ScrollableDetails,
    ) -> WidgetRef {
        ScrollBehaviorBase::build_scrollbar(self, app, context, child, details)
    }

    /// Applies a [`GlowingOverscrollIndicator`] to the child widget on
    /// [`TargetPlatform::Android`] and [`TargetPlatform::Fuchsia`].
    fn build_overscroll_indicator(
        &self,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
        details: &ScrollableDetails,
    ) -> WidgetRef {
        ScrollBehaviorBase::build_overscroll_indicator(self, app, context, child, details)
    }

    /// Specifies the type of velocity tracker to use in the descendant
    /// `Scrollable`s' drag gesture recognizers, for estimating the velocity of a
    /// drag gesture.
    ///
    /// This can be used to, for example, apply different fling velocity
    /// estimation methods on different platforms, in order to match the
    /// platform's native behavior.
    ///
    /// The default implementation provides a new
    /// [`IOSScrollViewFlingVelocityTracker`] on iOS and macOS for each new pointer,
    /// and a new [`VelocityTracker`] on other platforms for each new pointer.
    fn velocity_tracker_builder(
        &self,
        app: &mut App,
        context: BuildContext,
    ) -> GestureVelocityTrackerBuilder {
        ScrollBehaviorBase::velocity_tracker_builder(self, app, context)
    }

    /// The scroll physics to use for the platform given by
    /// [`get_platform`](Self::get_platform).
    ///
    /// Defaults to [`RangeMaintainingScrollPhysics`] mixed with
    /// [`BouncingScrollPhysics`] on iOS and [`ClampingScrollPhysics`] on
    /// Android.
    fn get_scroll_physics(&self, app: &mut App, context: BuildContext) -> ScrollPhysicsRef {
        ScrollBehaviorBase::get_scroll_physics(self, app, context)
    }

    /// Called whenever a [`ScrollConfiguration`] is rebuilt with a new
    /// [`ScrollBehavior`] of the same runtime type.
    ///
    /// If the new instance represents different information than the old
    /// instance, then the method should return true, otherwise it should return
    /// false.
    ///
    /// If this method returns true, all the widgets that inherit from the
    /// [`ScrollConfiguration`] will rebuild using the new [`ScrollBehavior`]. If this
    /// method returns false, the rebuilds might be optimized away.
    fn should_notify(&self, old_delegate: &dyn ScrollBehavior) -> bool {
        let _ = old_delegate;
        false
    }

    /// The default keyboard dismissal behavior for `ScrollView` widgets.
    ///
    /// Defaults to [`ScrollViewKeyboardDismissBehavior::Manual`].
    fn get_keyboard_dismiss_behavior(
        &self,
        app: &mut App,
        context: BuildContext,
    ) -> ScrollViewKeyboardDismissBehavior {
        let _ = (app, context);
        ScrollViewKeyboardDismissBehavior::Manual
    }
}

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

impl ScrollBehaviorBase {
    /// See [`ScrollBehavior::get_platform`].
    pub fn get_platform(app: &mut App, context: BuildContext) -> TargetPlatform {
        let _ = context;
        app.platform().target_platform()
    }

    /// See [`ScrollBehavior::drag_devices`].
    pub fn drag_devices() -> HashSet<PointerDeviceKind> {
        k_touch_like_device_types()
    }

    /// See [`ScrollBehavior::get_multitouch_drag_strategy`].
    pub fn get_multitouch_drag_strategy<B: ScrollBehavior + ?Sized>(
        behavior: &B,
        app: &mut App,
        context: BuildContext,
    ) -> MultitouchDragStrategy {
        match behavior.get_platform(app, context) {
            TargetPlatform::MacOS | TargetPlatform::IOS => {
                MultitouchDragStrategy::AverageBoundaryPointers
            }
            TargetPlatform::Linux
            | TargetPlatform::Windows
            | TargetPlatform::Android
            | TargetPlatform::Fuchsia => MultitouchDragStrategy::LatestPointer,
        }
    }

    /// See [`ScrollBehavior::pointer_axis_modifiers`].
    pub fn pointer_axis_modifiers() -> HashSet<LogicalKeyboardKey> {
        HashSet::from([
            LogicalKeyboardKey::SHIFT_LEFT,
            LogicalKeyboardKey::SHIFT_RIGHT,
        ])
    }

    /// See [`ScrollBehavior::build_scrollbar`].
    pub fn build_scrollbar<B: ScrollBehavior + ?Sized>(
        behavior: &B,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
        details: &ScrollableDetails,
    ) -> WidgetRef {
        // When modifying this function, consider modifying the implementation in the
        // Cupertino subclass as well.
        match behavior.get_platform(app, context) {
            TargetPlatform::Linux | TargetPlatform::MacOS | TargetPlatform::Windows => {
                debug_assert!(details.controller.is_some());
                let mut scrollbar = RawScrollbar::new(child);
                if let Some(controller) = details.controller.clone() {
                    scrollbar = scrollbar.controller(controller);
                }
                scrollbar.into_widget()
            }
            TargetPlatform::Android | TargetPlatform::Fuchsia | TargetPlatform::IOS => child,
        }
    }

    /// See [`ScrollBehavior::build_overscroll_indicator`].
    pub fn build_overscroll_indicator<B: ScrollBehavior + ?Sized>(
        behavior: &B,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
        details: &ScrollableDetails,
    ) -> WidgetRef {
        // When modifying this function, consider modifying the implementation in the
        // Material and Cupertino subclasses as well.
        match behavior.get_platform(app, context) {
            TargetPlatform::IOS
            | TargetPlatform::Linux
            | TargetPlatform::MacOS
            | TargetPlatform::Windows => child,
            TargetPlatform::Android | TargetPlatform::Fuchsia => {
                GlowingOverscrollIndicator::new(details.direction, K_DEFAULT_GLOW_COLOR)
                    .child(child)
                    .into_widget()
            }
        }
    }

    /// See [`ScrollBehavior::velocity_tracker_builder`].
    pub fn velocity_tracker_builder<B: ScrollBehavior + ?Sized>(
        behavior: &B,
        app: &mut App,
        context: BuildContext,
    ) -> GestureVelocityTrackerBuilder {
        match behavior.get_platform(app, context) {
            TargetPlatform::IOS => {
                Rc::new(|event| Box::new(IOSScrollViewFlingVelocityTracker::new(event.kind())))
            }
            TargetPlatform::MacOS => {
                Rc::new(|event| Box::new(MacOSScrollViewFlingVelocityTracker::new(event.kind())))
            }
            TargetPlatform::Android
            | TargetPlatform::Fuchsia
            | TargetPlatform::Linux
            | TargetPlatform::Windows => {
                Rc::new(|event| Box::new(VelocityTracker::with_kind(event.kind())))
            }
        }
    }

    /// Dart's `ScrollBehavior._bouncingPhysics`.
    fn bouncing_physics() -> ScrollPhysicsRef {
        Rc::new(
            BouncingScrollPhysics::new().with_parent(Rc::new(RangeMaintainingScrollPhysics::new())),
        )
    }

    /// Dart's `ScrollBehavior._bouncingDesktopPhysics`.
    fn bouncing_desktop_physics() -> ScrollPhysicsRef {
        Rc::new(
            BouncingScrollPhysics::new()
                .with_deceleration_rate(ScrollDecelerationRate::Fast)
                .with_parent(Rc::new(RangeMaintainingScrollPhysics::new())),
        )
    }

    /// Dart's `ScrollBehavior._clampingPhysics`.
    fn clamping_physics() -> ScrollPhysicsRef {
        Rc::new(
            ClampingScrollPhysics::new().with_parent(Rc::new(RangeMaintainingScrollPhysics::new())),
        )
    }

    /// See [`ScrollBehavior::get_scroll_physics`].
    pub fn get_scroll_physics<B: ScrollBehavior + ?Sized>(
        behavior: &B,
        app: &mut App,
        context: BuildContext,
    ) -> ScrollPhysicsRef {
        match behavior.get_platform(app, context) {
            TargetPlatform::IOS => ScrollBehaviorBase::bouncing_physics(),
            TargetPlatform::MacOS => ScrollBehaviorBase::bouncing_desktop_physics(),
            TargetPlatform::Android
            | TargetPlatform::Fuchsia
            | TargetPlatform::Linux
            | TargetPlatform::Windows => ScrollBehaviorBase::clamping_physics(),
        }
    }
}

/// Dart's instantiable `const ScrollBehavior()`.
#[derive(Clone, Copy, Default, PartialEq, Eq)]
pub struct PlainScrollBehavior;

impl PlainScrollBehavior {
    /// Creates a description of how `Scrollable` widgets should behave.
    pub const fn new() -> PlainScrollBehavior {
        PlainScrollBehavior
    }
}

impl ScrollBehavior for PlainScrollBehavior {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Debug for PlainScrollBehavior {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Dart's `objectRuntimeType(this, 'ScrollBehavior')`.
        f.write_str("ScrollBehavior")
    }
}

/// A [`ScrollBehavior`] held by value: what a Dart field or parameter typed `ScrollBehavior`
/// becomes.
///
/// It is a newtype rather than a bare `Rc` so that [`copy_with`](Self::copy_with) — which
/// Dart writes as a method capturing `this` as the new wrapper's delegate — has an `Rc` to
/// capture.
#[derive(Clone)]
pub struct ScrollBehaviorRef(Rc<dyn ScrollBehavior>);

impl ScrollBehaviorRef {
    /// Erases a [`ScrollBehavior`].
    pub fn new(behavior: impl ScrollBehavior) -> ScrollBehaviorRef {
        ScrollBehaviorRef(Rc::new(behavior))
    }

    /// Dart's `const ScrollBehavior()`.
    pub fn plain() -> ScrollBehaviorRef {
        ScrollBehaviorRef::new(PlainScrollBehavior::new())
    }

    /// Creates a copy of this behavior, making it possible to
    /// easily toggle `scrollbars` and `overscroll` effects.
    ///
    /// This is used by widgets like `PageView` and `ListWheelScrollView` to
    /// override the current [`ScrollBehavior`] and manage how they are decorated.
    ///
    /// The result is a [`WrappedScrollBehavior`], whose fluent setters are Dart's named
    /// arguments; copying a wrapper flattens it, as Dart's
    /// `_WrappedScrollBehavior.copyWith` does.
    pub fn copy_with(&self) -> WrappedScrollBehavior {
        match self.0.as_any().downcast_ref::<WrappedScrollBehavior>() {
            Some(wrapped) => WrappedScrollBehavior {
                delegate: wrapped.delegate.clone(),
                scrollbars: wrapped.scrollbars,
                overscroll: wrapped.overscroll,
                drag_devices: Some(ScrollBehavior::drag_devices(wrapped)),
                multitouch_drag_strategy: wrapped.multitouch_drag_strategy,
                pointer_axis_modifiers: Some(ScrollBehavior::pointer_axis_modifiers(wrapped)),
                physics: wrapped.physics.clone(),
                platform: wrapped.platform,
                keyboard_dismiss_behavior: wrapped.keyboard_dismiss_behavior,
            },
            None => WrappedScrollBehavior::new(self.clone()),
        }
    }

    /// Dart's `behavior.runtimeType`.
    pub fn type_id(&self) -> TypeId {
        self.0.as_any().type_id()
    }
}

impl Deref for ScrollBehaviorRef {
    type Target = dyn ScrollBehavior;

    fn deref(&self) -> &dyn ScrollBehavior {
        &*self.0
    }
}

impl PartialEq for ScrollBehaviorRef {
    fn eq(&self, other: &ScrollBehaviorRef) -> bool {
        // Dart's `==` on a `ScrollBehavior` is object identity.
        Rc::ptr_eq(&self.0, &other.0)
    }
}

impl Debug for ScrollBehaviorRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        Debug::fmt(&*self.0, f)
    }
}

/// The [`ScrollBehavior`] that [`ScrollBehaviorRef::copy_with`] returns; Dart's
/// `_WrappedScrollBehavior`.
#[derive(Clone)]
pub struct WrappedScrollBehavior {
    delegate: ScrollBehaviorRef,
    scrollbars: bool,
    overscroll: bool,
    drag_devices: Option<HashSet<PointerDeviceKind>>,
    multitouch_drag_strategy: Option<MultitouchDragStrategy>,
    pointer_axis_modifiers: Option<HashSet<LogicalKeyboardKey>>,
    physics: Option<ScrollPhysicsRef>,
    platform: Option<TargetPlatform>,
    keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
}

impl WrappedScrollBehavior {
    /// Wraps `delegate` with Dart's `copyWith` defaults: both decorations on and every other
    /// override unset.
    pub fn new(delegate: ScrollBehaviorRef) -> WrappedScrollBehavior {
        WrappedScrollBehavior {
            delegate,
            scrollbars: true,
            overscroll: true,
            drag_devices: None,
            multitouch_drag_strategy: None,
            pointer_axis_modifiers: None,
            physics: None,
            platform: None,
            keyboard_dismiss_behavior: None,
        }
    }

    /// Dart `copyWith(scrollbars:)`.
    pub fn scrollbars(mut self, scrollbars: bool) -> WrappedScrollBehavior {
        self.scrollbars = scrollbars;
        self
    }

    /// Dart `copyWith(overscroll:)`.
    pub fn overscroll(mut self, overscroll: bool) -> WrappedScrollBehavior {
        self.overscroll = overscroll;
        self
    }

    /// Dart `copyWith(dragDevices:)`.
    pub fn drag_devices(
        mut self,
        drag_devices: HashSet<PointerDeviceKind>,
    ) -> WrappedScrollBehavior {
        self.drag_devices = Some(drag_devices);
        self
    }

    /// Dart `copyWith(multitouchDragStrategy:)`.
    pub fn multitouch_drag_strategy(
        mut self,
        multitouch_drag_strategy: MultitouchDragStrategy,
    ) -> WrappedScrollBehavior {
        self.multitouch_drag_strategy = Some(multitouch_drag_strategy);
        self
    }

    /// Dart `copyWith(pointerAxisModifiers:)`.
    pub fn pointer_axis_modifiers(
        mut self,
        pointer_axis_modifiers: HashSet<LogicalKeyboardKey>,
    ) -> WrappedScrollBehavior {
        self.pointer_axis_modifiers = Some(pointer_axis_modifiers);
        self
    }

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

    /// Dart `copyWith(platform:)`.
    pub fn platform(mut self, platform: TargetPlatform) -> WrappedScrollBehavior {
        self.platform = Some(platform);
        self
    }

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

    /// The behavior this one decorates.
    pub fn delegate(&self) -> &ScrollBehaviorRef {
        &self.delegate
    }
}

impl ScrollBehavior for WrappedScrollBehavior {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn get_platform(&self, app: &mut App, context: BuildContext) -> TargetPlatform {
        self.platform
            .unwrap_or_else(|| self.delegate.get_platform(app, context))
    }

    fn drag_devices(&self) -> HashSet<PointerDeviceKind> {
        self.drag_devices
            .clone()
            .unwrap_or_else(|| self.delegate.drag_devices())
    }

    fn get_multitouch_drag_strategy(
        &self,
        app: &mut App,
        context: BuildContext,
    ) -> MultitouchDragStrategy {
        self.multitouch_drag_strategy
            .unwrap_or_else(|| self.delegate.get_multitouch_drag_strategy(app, context))
    }

    fn pointer_axis_modifiers(&self) -> HashSet<LogicalKeyboardKey> {
        self.pointer_axis_modifiers
            .clone()
            .unwrap_or_else(|| self.delegate.pointer_axis_modifiers())
    }

    fn build_scrollbar(
        &self,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
        details: &ScrollableDetails,
    ) -> WidgetRef {
        if self.scrollbars {
            return self.delegate.build_scrollbar(app, context, child, details);
        }
        child
    }

    fn build_overscroll_indicator(
        &self,
        app: &mut App,
        context: BuildContext,
        child: WidgetRef,
        details: &ScrollableDetails,
    ) -> WidgetRef {
        if self.overscroll {
            return self
                .delegate
                .build_overscroll_indicator(app, context, child, details);
        }
        child
    }

    fn velocity_tracker_builder(
        &self,
        app: &mut App,
        context: BuildContext,
    ) -> GestureVelocityTrackerBuilder {
        self.delegate.velocity_tracker_builder(app, context)
    }

    fn get_scroll_physics(&self, app: &mut App, context: BuildContext) -> ScrollPhysicsRef {
        self.physics
            .clone()
            .unwrap_or_else(|| self.delegate.get_scroll_physics(app, context))
    }

    fn get_keyboard_dismiss_behavior(
        &self,
        app: &mut App,
        context: BuildContext,
    ) -> ScrollViewKeyboardDismissBehavior {
        self.keyboard_dismiss_behavior
            .unwrap_or_else(|| self.delegate.get_keyboard_dismiss_behavior(app, context))
    }

    fn should_notify(&self, old_delegate: &dyn ScrollBehavior) -> bool {
        let old = old_delegate
            .as_any()
            .downcast_ref::<WrappedScrollBehavior>()
            .expect("a _WrappedScrollBehavior only compares against another one");
        old.delegate.type_id() != self.delegate.type_id()
            || old.scrollbars != self.scrollbars
            || old.overscroll != self.overscroll
            || ScrollBehavior::drag_devices(old) != ScrollBehavior::drag_devices(self)
            || old.multitouch_drag_strategy != self.multitouch_drag_strategy
            || ScrollBehavior::pointer_axis_modifiers(old)
                != ScrollBehavior::pointer_axis_modifiers(self)
            || !match (&old.physics, &self.physics) {
                (None, None) => true,
                (Some(old), Some(physics)) => Rc::ptr_eq(old, physics),
                _ => false,
            }
            || old.platform != self.platform
            || self.delegate.should_notify(&*old.delegate)
    }
}

impl Debug for WrappedScrollBehavior {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Dart's `objectRuntimeType(this, '_WrappedScrollBehavior')`.
        f.write_str("_WrappedScrollBehavior")
    }
}

/// Controls how `Scrollable` widgets behave in a subtree.
///
/// The scroll configuration determines the [`ScrollPhysics`](crate::ScrollPhysics) and viewport
/// decorations used by descendants of [`child`](Self::child).
#[derive(Debug)]
pub struct ScrollConfiguration {
    pub key: Option<KeyRef>,

    /// How `Scrollable` widgets that are descendants of [`child`](Self::child) should behave.
    pub behavior: ScrollBehaviorRef,

    /// The widget below this widget in the tree.
    pub child: WidgetRef,
}

impl ScrollConfiguration {
    /// Creates a widget that controls how `Scrollable` widgets behave in a subtree.
    pub fn new<K>(
        behavior: ScrollBehaviorRef,
        child: impl crate::framework::IntoWidget<K>,
    ) -> ScrollConfiguration {
        ScrollConfiguration {
            key: None,
            behavior,
            child: child.into_widget(),
        }
    }

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

    /// The [`ScrollBehavior`] for `Scrollable` widgets in the given [`BuildContext`].
    ///
    /// If no [`ScrollConfiguration`] widget is in scope of the given `context`,
    /// a default [`PlainScrollBehavior`] is returned.
    pub fn of(app: &mut App, context: BuildContext) -> ScrollBehaviorRef {
        context
            .depend_on_inherited_widget_of_exact_type::<ScrollConfiguration>(app)
            .map(|configuration| configuration.behavior.clone())
            .unwrap_or_else(ScrollBehaviorRef::plain)
    }
}

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

    fn child(&self) -> &WidgetRef {
        &self.child
    }

    fn update_should_notify(&self, old_widget: &ScrollConfiguration) -> bool {
        self.behavior.type_id() != old_widget.behavior.type_id()
            || (self.behavior != old_widget.behavior
                && self.behavior.should_notify(&*old_widget.behavior))
    }
}

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

    use waft_test::TestPlatform;

    use super::*;
    use crate::framework::{AnyElement, Element, IntoWidget};
    use crate::test_harness::Harness;
    use crate::testing::{expect, find, finds_nothing, finds_one_widget, test_widgets};
    use crate::widgets::basic::SizedBox;

    fn app_on(platform: TargetPlatform) -> Rc<AppCell> {
        AppCell::with_platform(Rc::new(TestPlatform::new().on(platform)))
    }

    fn descendant(harness: &Harness, app: &App, depth: usize) -> AnyElement {
        let mut element = harness.root.as_element();
        for _ in 0..=depth {
            element = element.children(app)[0];
        }
        element
    }

    fn mount(app: &mut App, widget: crate::framework::WidgetRef) -> Harness {
        let harness = Harness::mount(app, widget);
        harness.pump(app);
        harness
    }

    #[test]
    fn the_default_behavior_picks_its_physics_from_the_platform() {
        for (platform, expected) in [
            (TargetPlatform::IOS, "BouncingScrollPhysics"),
            (TargetPlatform::MacOS, "BouncingScrollPhysics"),
            (TargetPlatform::Android, "ClampingScrollPhysics"),
            (TargetPlatform::Fuchsia, "ClampingScrollPhysics"),
            (TargetPlatform::Linux, "ClampingScrollPhysics"),
            (TargetPlatform::Windows, "ClampingScrollPhysics"),
        ] {
            let cell = app_on(platform);
            let mut app = cell.borrow_mut();
            let harness = mount(&mut app, SizedBox::shrink().into_widget());
            let context = descendant(&harness, &app, 0);

            let behavior = ScrollConfiguration::of(&mut app, context);
            assert_eq!(behavior.get_platform(&mut app, context), platform);
            let physics = behavior.get_scroll_physics(&mut app, context);
            let described = format!("{physics:?}");
            assert!(described.contains(expected), "{platform:?}: {described}");
            assert!(
                described.contains("RangeMaintainingScrollPhysics"),
                "{platform:?}: {described}"
            );
        }
    }

    #[test]
    fn of_falls_back_to_a_plain_behavior_and_reads_the_ambient_one() {
        let cell = app_on(TargetPlatform::Android);
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, SizedBox::shrink().into_widget());
        let context = descendant(&harness, &app, 0);
        assert_eq!(
            format!("{:?}", ScrollConfiguration::of(&mut app, context)),
            "ScrollBehavior"
        );

        let behavior = ScrollBehaviorRef::new(
            ScrollBehaviorRef::plain()
                .copy_with()
                .platform(TargetPlatform::IOS),
        );
        let harness = mount(
            &mut app,
            ScrollConfiguration::new(behavior, SizedBox::shrink()).into_widget(),
        );
        let context = descendant(&harness, &app, 1);
        let ambient = ScrollConfiguration::of(&mut app, context);
        assert_eq!(ambient.get_platform(&mut app, context), TargetPlatform::IOS);
        // As in Dart, `_WrappedScrollBehavior.getScrollPhysics` defers to the delegate, which
        // reads its own platform; only `copyWith(physics:)` replaces the physics.
        assert!(
            format!("{:?}", ambient.get_scroll_physics(&mut app, context))
                .contains("ClampingScrollPhysics")
        );

        let bouncing: ScrollPhysicsRef = Rc::new(BouncingScrollPhysics::new());
        let overridden = ScrollBehaviorRef::new(
            ScrollBehaviorRef::plain()
                .copy_with()
                .physics(bouncing.clone()),
        );
        assert!(Rc::ptr_eq(
            &overridden.get_scroll_physics(&mut app, context),
            &bouncing
        ));
    }

    #[test]
    fn copy_with_overrides_the_delegate_and_flattens_a_second_copy() {
        let plain = ScrollBehaviorRef::plain();
        let once = plain.copy_with().scrollbars(false);
        assert!(!once.scrollbars);
        assert!(once.overscroll);
        assert_eq!(once.delegate(), &plain);

        let twice = ScrollBehaviorRef::new(once).copy_with().overscroll(false);
        assert!(!twice.scrollbars);
        assert!(!twice.overscroll);
        // The second copy keeps the original delegate rather than nesting a wrapper.
        assert_eq!(twice.delegate().type_id(), plain.type_id());
    }

    #[test]
    fn the_default_behavior_flips_the_axes_for_shift_and_takes_touch_like_devices() {
        let cell = app_on(TargetPlatform::Android);
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, SizedBox::shrink().into_widget());
        let context = descendant(&harness, &app, 0);
        let behavior = ScrollConfiguration::of(&mut app, context);

        assert_eq!(
            behavior.pointer_axis_modifiers(),
            HashSet::from([
                LogicalKeyboardKey::SHIFT_LEFT,
                LogicalKeyboardKey::SHIFT_RIGHT
            ])
        );
        assert!(behavior.drag_devices().contains(&PointerDeviceKind::Touch));
        assert!(!behavior.drag_devices().contains(&PointerDeviceKind::Mouse));
        assert_eq!(
            behavior.get_multitouch_drag_strategy(&mut app, context),
            MultitouchDragStrategy::LatestPointer
        );
    }

    #[test]
    fn the_desktop_platforms_wrap_the_child_in_a_scrollbar() {
        for platform in [
            TargetPlatform::Linux,
            TargetPlatform::MacOS,
            TargetPlatform::Windows,
        ] {
            let cell = app_on(platform);
            let mut app = cell.borrow_mut();
            let harness = mount(&mut app, SizedBox::shrink().into_widget());
            let context = descendant(&harness, &app, 0);
            let behavior = ScrollConfiguration::of(&mut app, context);
            let controller = crate::widgets::scroll_controller::ScrollController::default(&mut app);
            let details = ScrollableDetails::vertical(false).controller(controller.erase());

            let child = SizedBox::shrink().into_widget();
            let scrollbar = behavior.build_scrollbar(&mut app, context, child.clone(), &details);
            assert!(
                crate::framework::downcast_widget::<RawScrollbar>(&*scrollbar).is_some(),
                "{platform:?} decorates the child with a RawScrollbar"
            );
            let indicator =
                behavior.build_overscroll_indicator(&mut app, context, child.clone(), &details);
            assert!(
                Rc::ptr_eq(&indicator, &child),
                "{platform:?} shows no overscroll indicator"
            );
        }
    }

    #[test]
    fn ios_decorates_the_child_with_neither_a_scrollbar_nor_an_indicator() {
        let cell = app_on(TargetPlatform::IOS);
        let mut app = cell.borrow_mut();
        let harness = mount(&mut app, SizedBox::shrink().into_widget());
        let context = descendant(&harness, &app, 0);
        let behavior = ScrollConfiguration::of(&mut app, context);
        let details = ScrollableDetails::vertical(false);

        let child = SizedBox::shrink().into_widget();
        let scrollbar = behavior.build_scrollbar(&mut app, context, child.clone(), &details);
        assert!(Rc::ptr_eq(&scrollbar, &child));
        let indicator =
            behavior.build_overscroll_indicator(&mut app, context, child.clone(), &details);
        assert!(Rc::ptr_eq(&indicator, &child));
    }

    #[test]
    fn android_and_fuchsia_wrap_the_child_in_a_white_glow_along_the_scroll_direction() {
        for platform in [TargetPlatform::Android, TargetPlatform::Fuchsia] {
            let cell = app_on(platform);
            let mut app = cell.borrow_mut();
            let harness = mount(&mut app, SizedBox::shrink().into_widget());
            let context = descendant(&harness, &app, 0);
            let behavior = ScrollConfiguration::of(&mut app, context);
            let details = ScrollableDetails::vertical(true);

            let child = SizedBox::shrink().into_widget();
            let scrollbar = behavior.build_scrollbar(&mut app, context, child.clone(), &details);
            assert!(Rc::ptr_eq(&scrollbar, &child), "{platform:?}");
            let indicator =
                behavior.build_overscroll_indicator(&mut app, context, child.clone(), &details);
            let glow = crate::framework::downcast_widget::<GlowingOverscrollIndicator>(&*indicator)
                .unwrap_or_else(|| panic!("{platform:?} glows"));
            assert_eq!(glow.axis_direction, waft_painting::AxisDirection::Up);
            assert_eq!(glow.color, Color::new(0xFFFFFFFF));
            assert!(Rc::ptr_eq(
                glow.child.as_ref().expect("the glow wraps the child"),
                &child
            ));
        }
    }

    fn list_under(behavior: ScrollBehaviorRef) -> crate::framework::WidgetRef {
        crate::widgets::basic::Directionality::new(
            waft_embedder::TextDirection::Ltr,
            ScrollConfiguration::new(
                behavior,
                crate::widgets::scroll_view::ListView::new()
                    .children([SizedBox::new().height(1000.0).width(1000.0).into_widget()]),
            ),
        )
        .into_widget()
    }

    /// `scroll_behavior_test.dart`: "ScrollBehavior default android overscroll indicator".
    #[test]
    fn the_default_behavior_glows_on_android() {
        test_widgets(|tester| {
            tester.pump_widget(list_under(ScrollBehaviorRef::plain()));

            expect(
                tester,
                &find::by_type::<crate::widgets::overscroll_indicator::StretchingOverscrollIndicator>(
                ),
                finds_nothing(),
            );
            expect(
                tester,
                &find::by_type::<GlowingOverscrollIndicator>(),
                finds_one_widget(),
            );
        });
    }

    /// `scroll_behavior_test.dart`: "ScrollBehavior configuration is maintained over multiple
    /// copies": "overscroll".
    #[test]
    fn a_copy_without_overscroll_keeps_the_glow_off_through_a_second_copy() {
        test_widgets(|tester| {
            let glows = find::by_type::<GlowingOverscrollIndicator>;
            let default_behavior = ScrollBehaviorRef::plain();
            tester.pump_widget(list_under(default_behavior.clone()));
            // Default adds a glowing overscroll indicator
            expect(tester, &glows(), finds_one_widget());

            let once_copied_behavior =
                ScrollBehaviorRef::new(default_behavior.copy_with().overscroll(false));
            tester.pump_widget(list_under(once_copied_behavior.clone()));
            // Copy does not add indicator
            expect(tester, &glows(), finds_nothing());

            let twice_copied_behavior = ScrollBehaviorRef::new(once_copied_behavior.copy_with());
            tester.pump_widget(list_under(twice_copied_behavior));
            // Second copy maintains overscroll setting
            expect(tester, &glows(), finds_nothing());
        });
    }
}