Skip to main content

waft_widgets/widgets/
draggable_scrollable_sheet.rs

1//! Flutter counterpart: `widgets/draggable_scrollable_sheet.dart`.
2
3use std::cell::Cell;
4use std::fmt::{self, Debug};
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_animation::{Animation, AnimationBehavior, AnimationController, Curve};
9use waft_embedder::clamp_double;
10use waft_foundation::{
11    App, ChangeNotifier, ChangeNotifierData, CompleterFuture, Handle, ListenableObject, Listener,
12    OptionRetained, ValueListenable, ValueNotifier,
13};
14use waft_gestures::{Drag, DragStartDetails};
15use waft_painting::AlignmentGeometry;
16use waft_physics::{Simulation, Tolerance};
17use waft_scheduler::{FrameCallback, SchedulerBinding};
18
19use crate::framework::{
20    BuildContext, IntoWidget, KeyRef, Notification, State, StateData, StatefulWidget, WidgetRef,
21};
22use crate::view::View;
23use crate::widgets::basic::{FractionallySizedBox, SizedBox};
24use crate::widgets::inherited_notifier::{InheritedNotifier, InheritedNotifierKind};
25use crate::widgets::layout_builder::LayoutBuilder;
26use crate::widgets::scroll_activity::ScrollActivityRef;
27use crate::widgets::scroll_context::ScrollContext;
28use crate::widgets::scroll_controller::{
29    ScrollController, ScrollControllerData, ScrollControllerLeaf, ScrollControllerRef,
30};
31use crate::widgets::scroll_notification::{ViewportNotificationData, ViewportNotificationMixin};
32use crate::widgets::scroll_physics::{AlwaysScrollableScrollPhysics, ScrollPhysicsRef};
33use crate::widgets::scroll_position::{
34    AnyScrollPosition, ScrollPosition, ScrollPositionData, ScrollPositionRef,
35};
36use crate::widgets::scroll_position_with_single_context::{
37    ScrollPositionWithSingleContext, ScrollPositionWithSingleContextData,
38    ScrollPositionWithSingleContextLeaf,
39};
40use crate::widgets::scroll_simulation::ClampingScrollSimulation;
41use crate::widgets::value_listenable_builder::ValueListenableBuilder;
42use crate::{InheritedWidget, ScrollActivityDelegate};
43use waft_foundation::Ref;
44
45/// The signature of a method that provides a [`BuildContext`] and
46/// `ScrollController` for building a widget that may overflow the draggable
47/// [`Axis`](waft_painting::Axis) of the containing area.
48///
49/// This builder is used when a widget is expected to have a scrollable child
50/// widget, and a vertical gesture needs to trigger scrolling and some other behavior
51/// during that same gesture.
52///
53/// For example, users of [`DraggableScrollableSheet`] should apply the scroll controller
54/// to a scroll view such as `SingleChildScrollView` or `ListView`, to have the whole sheet
55/// be draggable.
56pub type ScrollableWidgetBuilder =
57    Rc<dyn Fn(&mut App, BuildContext, ScrollControllerRef) -> WidgetRef>;
58
59/// Dart's `_DraggableSheetExtent Function()`: the sheet's current extent, which the state
60/// replaces on every rebuild.
61type GetSheetExtent = Rc<dyn Fn(&App) -> Handle<DraggableSheetExtent>>;
62
63// ---------------------------------------------------------------------------------------------
64// DraggableScrollableController
65
66/// Controls a [`DraggableScrollableSheet`].
67///
68/// Draggable scrollable controllers are typically stored as member variables in
69/// `State` objects and are reused in each `State::build`. Controllers can only
70/// be used to control one sheet at a time. A controller can be reused with a
71/// new sheet if the previous sheet has been disposed.
72///
73/// The controller's methods cannot be used until after the controller has been
74/// passed into a [`DraggableScrollableSheet`] and the sheet has run `init_state`.
75///
76/// A [`DraggableScrollableController`] is a
77/// [`Listenable`](waft_foundation::Listenable). It notifies its listeners whenever an
78/// attached sheet changes sizes. It does not notify its listeners when a sheet is first
79/// attached or when an attached sheet's parameters change without affecting the sheet's
80/// current size. It does not fire when [`pixels`](Self::pixels) changes without
81/// [`size`](Self::size) changing. For example, if the constraints provided to an attached
82/// sheet change.
83pub struct DraggableScrollableController {
84    change_notifier: ChangeNotifierData,
85    attached_controller: Option<Ref<DraggableScrollableSheetScrollController>>,
86    animation_controllers: Vec<Ref<AnimationController>>,
87}
88
89impl DraggableScrollableController {
90    /// Creates a controller for [`DraggableScrollableSheet`].
91    pub fn new(app: &mut App) -> Ref<DraggableScrollableController> {
92        app.create(DraggableScrollableController {
93            change_notifier: ChangeNotifierData::new(),
94            attached_controller: None,
95            animation_controllers: Vec::new(),
96        })
97    }
98
99    /// Get the current size (as a fraction of the parent height) of the attached sheet.
100    pub fn size(self: Handle<Self>, app: &App) -> f64 {
101        self.assert_attached(app);
102        self.extent(app).current_size(app)
103    }
104
105    /// Get the current pixel height of the attached sheet.
106    pub fn pixels(self: Handle<Self>, app: &App) -> f64 {
107        self.assert_attached(app);
108        let extent = self.extent(app);
109        extent.current_pixels(app)
110    }
111
112    /// Convert a sheet's size (fractional value of parent container height) to pixels.
113    pub fn size_to_pixels(self: Handle<Self>, app: &App, size: f64) -> f64 {
114        self.assert_attached(app);
115        self.extent(app).size_to_pixels(app, size)
116    }
117
118    /// Whether a [`DraggableScrollableController`] has attached itself to a
119    /// [`DraggableScrollableSheet`].
120    ///
121    /// If this is false, then members that interact with the `ScrollPosition`,
122    /// such as [`size_to_pixels`](Self::size_to_pixels), [`size`](Self::size),
123    /// [`animate_to`](Self::animate_to), and [`jump_to`](Self::jump_to), must not be called.
124    pub fn is_attached(self: Handle<Self>, app: &App) -> bool {
125        app.get(self)
126            .attached_controller
127            .as_ref()
128            .is_some_and(|controller| controller.has_clients(app))
129    }
130
131    /// Convert a sheet's pixel height to size (fractional value of parent container height).
132    pub fn pixels_to_size(self: Handle<Self>, app: &App, pixels: f64) -> f64 {
133        self.assert_attached(app);
134        self.extent(app).pixels_to_size(app, pixels)
135    }
136
137    /// Animates the attached sheet from its current size to the given `size`, a
138    /// fractional value of the parent container's height.
139    ///
140    /// Any active sheet animation is canceled. If the sheet's internal scrollable
141    /// is currently animating (e.g. responding to a user fling), that animation is
142    /// canceled as well.
143    ///
144    /// An animation will be interrupted whenever the user attempts to scroll
145    /// manually, whenever another activity is started, or when the sheet hits its
146    /// max or min size (e.g. if you animate to 1 but the max size is .8, the
147    /// animation will stop playing when it reaches .8).
148    ///
149    /// The duration must not be zero. To jump to a particular value without an
150    /// animation, use [`jump_to`](Self::jump_to).
151    ///
152    /// The sheet will not snap after calling [`animate_to`](Self::animate_to) even if
153    /// [`DraggableScrollableSheet::snap`] is true. Snapping only occurs after user drags.
154    ///
155    /// The returned future completes when the animation ends. An interrupted animation is
156    /// stopped as canceled, so its future never completes — as Dart's does not.
157    pub fn animate_to(
158        self: Handle<Self>,
159        app: &mut App,
160        size: f64,
161        duration: Duration,
162        curve: Rc<dyn Curve>,
163    ) -> CompleterFuture<()> {
164        self.assert_attached(app);
165        debug_assert!((0.0..=1.0).contains(&size));
166        debug_assert!(!duration.is_zero());
167        let attached = self.attached_controller(app);
168        let extent = app.get(attached).extent.clone();
169        let position = attached.position(app);
170        let vsync = position.context(app).vsync();
171        let animation_controller = AnimationController::unbounded(
172            app,
173            extent.current_size(app),
174            None,
175            None,
176            AnimationBehavior::Preserve,
177            vsync,
178        );
179        app.get_mut(self)
180            .animation_controllers
181            .push(animation_controller.clone());
182        ScrollActivityDelegate::go_idle(position, app);
183        // This disables any snapping until the next user interaction with the sheet.
184        app.get_mut(&extent).has_dragged = false;
185        app.get_mut(&extent).has_changed = true;
186        let canceled = animation_controller.clone();
187        extent.start_activity(
188            app,
189            Listener::new(move |app| {
190                // Don't stop the controller if it's already finished and may have been
191                // disposed.
192                if canceled.is_animating(app) {
193                    canceled.stop(app, true);
194                }
195            }),
196        );
197        let ticking = animation_controller.handle();
198        Animation::add_listener(
199            ticking,
200            app,
201            Listener::new(move |app: &mut App| {
202                let value = ticking.value(app);
203                let position = self.attached_controller(app).position(app);
204                let context = position.context(app).notification_context(app);
205                extent.update_size(app, value, context.expect("a mounted scrollable"));
206            }),
207        );
208        let extent = self.extent(app);
209        let target = clamp_double(size, extent.min_size(app), extent.max_size(app));
210        let animated = animation_controller.animate_to(app, target, Some(duration), curve);
211        CompleterFuture::spawn(app, animated)
212    }
213
214    /// Jumps the attached sheet from its current size to the given `size`, a
215    /// fractional value of the parent container's height.
216    ///
217    /// If `size` is outside of the attached sheet's min or max child size,
218    /// [`jump_to`](Self::jump_to) will jump the sheet to the nearest valid size instead.
219    ///
220    /// Any active sheet animation is canceled. If the sheet's inner scrollable
221    /// is currently animating (e.g. responding to a user fling), that animation is
222    /// canceled as well.
223    ///
224    /// The sheet will not snap after calling [`jump_to`](Self::jump_to) even if
225    /// [`DraggableScrollableSheet::snap`] is true. Snapping only occurs after user drags.
226    pub fn jump_to(self: Handle<Self>, app: &mut App, size: f64) {
227        self.assert_attached(app);
228        debug_assert!((0.0..=1.0).contains(&size));
229        let extent = self.extent(app);
230        let position = self.attached_controller(app).position(app);
231        // Call start activity to interrupt any other playing activities.
232        extent.start_activity(app, Listener::new(|_app| {}));
233        ScrollActivityDelegate::go_idle(position, app);
234        app.get_mut(extent).has_dragged = false;
235        app.get_mut(extent).has_changed = true;
236        let context = position.context(app).notification_context(app);
237        extent.update_size(app, size, context.expect("a mounted scrollable"));
238    }
239
240    /// Reset the attached sheet to its initial size (see
241    /// [`DraggableScrollableSheet::initial_child_size`]).
242    pub fn reset(self: Handle<Self>, app: &mut App) {
243        self.assert_attached(app);
244        self.attached_controller(app).reset(app);
245    }
246
247    /// Discards any resources used by the object.
248    pub fn dispose(self: Handle<Self>, app: &mut App) {
249        ChangeNotifierData::dispose(app, self);
250    }
251
252    fn assert_attached(self: Handle<Self>, app: &App) {
253        debug_assert!(
254            self.is_attached(app),
255            "DraggableScrollableController is not attached to a sheet. A \
256             DraggableScrollableController must be used in a DraggableScrollableSheet before \
257             any of its methods are called."
258        );
259    }
260
261    fn attached_controller(
262        self: Handle<Self>,
263        app: &App,
264    ) -> Handle<DraggableScrollableSheetScrollController> {
265        app.get(self)
266            .attached_controller
267            .handle()
268            .expect("the controller is attached to a sheet")
269    }
270
271    fn extent(self: Handle<Self>, app: &App) -> Handle<DraggableSheetExtent> {
272        app.get(self.attached_controller(app)).extent.handle()
273    }
274
275    /// Dart's `notifyListeners` tear-off, which the extent's size is listened to with.
276    fn notification_listener(self: Handle<Self>) -> Listener {
277        Listener::handle_method(self, DraggableScrollableController::forward_notification)
278    }
279
280    fn forward_notification(self: Handle<Self>, app: &mut App) {
281        self.notify_listeners(app);
282    }
283
284    fn attach(
285        self: Handle<Self>,
286        app: &mut App,
287        scroll_controller: Ref<DraggableScrollableSheetScrollController>,
288    ) {
289        debug_assert!(
290            app.get(self).attached_controller.is_none(),
291            "Draggable scrollable controller is already attached to a sheet."
292        );
293        app.get_mut(self).attached_controller = Some(scroll_controller.clone());
294        let current_size = app
295            .get(&app.get(&scroll_controller).extent)
296            .current_size
297            .handle();
298        let listener = self.notification_listener();
299        ListenableObject::add_listener(current_size, app, listener);
300        app.get_mut(&scroll_controller).on_position_detached = Some(Listener::handle_method(
301            self,
302            DraggableScrollableController::dispose_animation_controllers,
303        ));
304    }
305
306    fn on_extent_replaced(
307        self: Handle<Self>,
308        app: &mut App,
309        previous_extent: Handle<DraggableSheetExtent>,
310    ) {
311        // When the extent has been replaced, the old extent is already disposed and
312        // the controller will point to a new extent. We have to add our listener to
313        // the new extent.
314        let extent = self.extent(app);
315        let current_size = app.get(extent).current_size.handle();
316        let listener = self.notification_listener();
317        ListenableObject::add_listener(current_size, app, listener);
318        if previous_extent.current_size(app) != extent.current_size(app) {
319            // The listener won't fire for a change in size between two extent
320            // objects so we have to fire it manually here.
321            self.notify_listeners(app);
322        }
323    }
324
325    fn detach(self: Handle<Self>, app: &mut App, dispose_extent: bool) {
326        if let Some(attached_controller) = app.get(self).attached_controller.handle() {
327            let extent = app.get(attached_controller).extent.handle();
328            if dispose_extent {
329                extent.dispose(app);
330            } else {
331                let current_size = app.get(extent).current_size.handle();
332                ListenableObject::remove_listener(current_size, app, &self.notification_listener());
333            }
334        }
335        self.dispose_animation_controllers(app);
336        app.get_mut(self).attached_controller = None;
337    }
338
339    fn dispose_animation_controllers(self: Handle<Self>, app: &mut App) {
340        for animation_controller in std::mem::take(&mut app.get_mut(self).animation_controllers) {
341            animation_controller.dispose(app);
342        }
343    }
344}
345
346impl ChangeNotifier for DraggableScrollableController {
347    fn change_notifier_data(&self) -> &ChangeNotifierData {
348        &self.change_notifier
349    }
350
351    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
352        &mut self.change_notifier
353    }
354}
355
356// ---------------------------------------------------------------------------------------------
357// DraggableScrollableSheet
358
359/// A container for a `Scrollable` that responds to drag gestures by resizing
360/// the scrollable until a limit is reached, and then scrolling.
361///
362/// This widget can be dragged along the vertical axis between its
363/// [`min_child_size`](Self::min_child_size), which defaults to `0.25` and
364/// [`max_child_size`](Self::max_child_size), which defaults to `1.0`. These sizes are
365/// percentages of the height of the parent container.
366///
367/// The widget coordinates resizing and scrolling of the widget returned by
368/// builder as the user drags along the horizontal axis.
369///
370/// The widget will initially be displayed at its
371/// [`initial_child_size`](Self::initial_child_size) which defaults to `0.5`, meaning half the
372/// height of its parent. Dragging will work between the range of
373/// [`min_child_size`](Self::min_child_size) and [`max_child_size`](Self::max_child_size) (as
374/// percentages of the parent container's height) as long as the builder creates a widget
375/// which uses the provided scroll controller. If the widget created by the
376/// [`ScrollableWidgetBuilder`] does not use the provided controller, the sheet will remain at
377/// the initial child size.
378///
379/// By default, the widget will stay at whatever size the user drags it to. To
380/// make the widget snap to specific sizes whenever they lift their finger
381/// during a drag, set [`snap`](Self::snap) to `true`. The sheet will snap between
382/// [`min_child_size`](Self::min_child_size) and [`max_child_size`](Self::max_child_size). Use
383/// [`snap_sizes`](Self::snap_sizes) to add more sizes for the sheet to snap between.
384///
385/// The snapping effect is only applied on user drags. Programmatically
386/// manipulating the sheet size via [`DraggableScrollableController::animate_to`] or
387/// [`DraggableScrollableController::jump_to`] will ignore [`snap`](Self::snap) and
388/// [`snap_sizes`](Self::snap_sizes).
389///
390/// By default, the widget will expand its non-occupied area to fill available
391/// space in the parent. If this is not desired, e.g. because the parent wants
392/// to position sheet based on the space it is taking, the [`expand`](Self::expand) property
393/// may be set to false.
394pub struct DraggableScrollableSheet {
395    /// See `Widget::key`.
396    pub key: Option<KeyRef>,
397    /// The initial fractional value of the parent container's height to use when
398    /// displaying the widget.
399    ///
400    /// Rebuilding the sheet with a new initial child size will only move
401    /// the sheet to the new value if the sheet has not yet been dragged since it
402    /// was first built or since the last call to [`DraggableScrollableActuator::reset`].
403    ///
404    /// The default value is `0.5`.
405    pub initial_child_size: f64,
406    /// The minimum fractional value of the parent container's height to use when
407    /// displaying the widget.
408    ///
409    /// The default value is `0.25`.
410    pub min_child_size: f64,
411    /// The maximum fractional value of the parent container's height to use when
412    /// displaying the widget.
413    ///
414    /// The default value is `1.0`.
415    pub max_child_size: f64,
416    /// Whether the widget should expand to fill the available space in its parent
417    /// or not.
418    ///
419    /// In most cases, this should be true. However, in the case of a parent
420    /// widget that will position this one based on its desired size (such as a
421    /// `Center`), this should be set to false.
422    ///
423    /// The default value is true.
424    pub expand: bool,
425    /// Whether the widget should snap between [`snap_sizes`](Self::snap_sizes) when the user
426    /// lifts their finger during a drag.
427    ///
428    /// If the user's finger was still moving when they lifted it, the widget will
429    /// snap to the next snap size in the direction of the drag. If their finger was still,
430    /// the widget will snap to the nearest snap size.
431    ///
432    /// Snapping is not applied when the sheet is programmatically moved by
433    /// calling [`DraggableScrollableController::animate_to`] or
434    /// [`DraggableScrollableController::jump_to`].
435    ///
436    /// Rebuilding the sheet with snap newly enabled will immediately trigger a
437    /// snap unless the sheet has not yet been dragged away from
438    /// [`initial_child_size`](Self::initial_child_size) since first being built or since the
439    /// last call to [`DraggableScrollableActuator::reset`].
440    pub snap: bool,
441    /// A list of target sizes that the widget should snap to.
442    ///
443    /// Snap sizes are fractional values of the parent container's height. They
444    /// must be listed in increasing order and be between
445    /// [`min_child_size`](Self::min_child_size) and
446    /// [`max_child_size`](Self::max_child_size).
447    ///
448    /// The minimum and maximum child sizes are implicitly included in snap
449    /// sizes and do not need to be specified here.
450    pub snap_sizes: Option<Vec<f64>>,
451    /// Defines a duration for the snap animations.
452    ///
453    /// If it's not set, then the animation duration is the distance to the snap
454    /// target divided by the velocity of the widget.
455    pub snap_animation_duration: Option<Duration>,
456    /// A controller that can be used to programmatically control this sheet.
457    pub controller: Option<Ref<DraggableScrollableController>>,
458    /// Whether the sheet, when dragged (or flung) to its minimum size, should
459    /// cause its parent sheet to close.
460    ///
461    /// Set on emitted [`DraggableScrollableNotification`]s. It is up to parent
462    /// widgets to properly read and handle this value.
463    pub should_close_on_min_extent: bool,
464    /// The builder that creates a child to display in this widget, which will
465    /// use the provided scroll controller to enable dragging and scrolling
466    /// of the contents.
467    pub builder: ScrollableWidgetBuilder,
468}
469
470impl DraggableScrollableSheet {
471    /// Creates a widget that can be dragged and scrolled in a single gesture; Dart's optional
472    /// arguments are the setters.
473    ///
474    /// Dart's defaults: `initial_child_size` 0.5, `min_child_size` 0.25, `max_child_size` 1.0,
475    /// `expand` true, `snap` false, `should_close_on_min_extent` true.
476    pub fn new(builder: ScrollableWidgetBuilder) -> DraggableScrollableSheet {
477        DraggableScrollableSheet {
478            key: None,
479            initial_child_size: 0.5,
480            min_child_size: 0.25,
481            max_child_size: 1.0,
482            expand: true,
483            snap: false,
484            snap_sizes: None,
485            snap_animation_duration: None,
486            controller: None,
487            should_close_on_min_extent: true,
488            builder,
489        }
490    }
491
492    /// Dart `DraggableScrollableSheet(key:)`.
493    pub fn key(mut self, key: KeyRef) -> DraggableScrollableSheet {
494        self.key = Some(key);
495        self
496    }
497
498    /// Dart `DraggableScrollableSheet(initialChildSize:)`.
499    pub fn initial_child_size(mut self, initial_child_size: f64) -> DraggableScrollableSheet {
500        self.initial_child_size = initial_child_size;
501        self
502    }
503
504    /// Dart `DraggableScrollableSheet(minChildSize:)`.
505    pub fn min_child_size(mut self, min_child_size: f64) -> DraggableScrollableSheet {
506        self.min_child_size = min_child_size;
507        self
508    }
509
510    /// Dart `DraggableScrollableSheet(maxChildSize:)`.
511    pub fn max_child_size(mut self, max_child_size: f64) -> DraggableScrollableSheet {
512        self.max_child_size = max_child_size;
513        self
514    }
515
516    /// Dart `DraggableScrollableSheet(expand:)`.
517    pub fn expand(mut self, expand: bool) -> DraggableScrollableSheet {
518        self.expand = expand;
519        self
520    }
521
522    /// Dart `DraggableScrollableSheet(snap:)`.
523    pub fn snap(mut self, snap: bool) -> DraggableScrollableSheet {
524        self.snap = snap;
525        self
526    }
527
528    /// Dart `DraggableScrollableSheet(snapSizes:)`.
529    pub fn snap_sizes(mut self, snap_sizes: Vec<f64>) -> DraggableScrollableSheet {
530        self.snap_sizes = Some(snap_sizes);
531        self
532    }
533
534    /// Dart `DraggableScrollableSheet(snapAnimationDuration:)`.
535    pub fn snap_animation_duration(mut self, duration: Duration) -> DraggableScrollableSheet {
536        debug_assert!(!duration.is_zero());
537        self.snap_animation_duration = Some(duration);
538        self
539    }
540
541    /// Dart `DraggableScrollableSheet(controller:)`.
542    pub fn controller(
543        mut self,
544        controller: Ref<DraggableScrollableController>,
545    ) -> DraggableScrollableSheet {
546        self.controller = Some(controller);
547        self
548    }
549
550    /// Dart `DraggableScrollableSheet(shouldCloseOnMinExtent:)`.
551    pub fn should_close_on_min_extent(
552        mut self,
553        should_close_on_min_extent: bool,
554    ) -> DraggableScrollableSheet {
555        self.should_close_on_min_extent = should_close_on_min_extent;
556        self
557    }
558}
559
560impl Debug for DraggableScrollableSheet {
561    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
562        f.debug_struct("DraggableScrollableSheet")
563            .field("initialChildSize", &self.initial_child_size)
564            .field("minChildSize", &self.min_child_size)
565            .field("maxChildSize", &self.max_child_size)
566            .finish_non_exhaustive()
567    }
568}
569
570impl StatefulWidget for DraggableScrollableSheet {
571    type State = DraggableScrollableSheetState;
572
573    fn key(&self) -> Option<&KeyRef> {
574        self.key.as_ref()
575    }
576
577    fn create_state(&self) -> DraggableScrollableSheetState {
578        debug_assert!(self.min_child_size >= 0.0);
579        debug_assert!(self.max_child_size <= 1.0);
580        debug_assert!(self.min_child_size <= self.initial_child_size);
581        debug_assert!(self.initial_child_size <= self.max_child_size);
582        DraggableScrollableSheetState {
583            state: StateData::new(),
584            scroll_controller: None,
585            extent: None,
586        }
587    }
588}
589
590// ---------------------------------------------------------------------------------------------
591// DraggableScrollableNotification
592
593/// A [`Notification`] related to the extent, which is the size, and scroll
594/// offset, which is the position of the child list, of the
595/// [`DraggableScrollableSheet`].
596///
597/// [`DraggableScrollableSheet`] widgets notify their ancestors when the size of
598/// the sheet changes. When the extent of the sheet changes via a drag,
599/// this notification bubbles up through the tree, which means a given
600/// `NotificationListener` will receive notifications for all descendant
601/// [`DraggableScrollableSheet`] widgets. To focus on notifications from the
602/// nearest [`DraggableScrollableSheet`] descendant, check that the
603/// [`depth`](ViewportNotificationMixin::depth) property of the notification is zero.
604///
605/// When an extent notification is received by a `NotificationListener`, the
606/// listener will already have completed build and layout, and it is therefore
607/// too late for that widget to call `State::set_state`. Any attempt to adjust the
608/// build or layout based on an extent notification would result in a layout
609/// that lagged one frame behind, which is a poor user experience. Extent
610/// notifications are used primarily to drive animations.
611pub struct DraggableScrollableNotification {
612    viewport_notification: ViewportNotificationData,
613    /// The current value of the extent, between [`min_extent`](Self::min_extent) and
614    /// [`max_extent`](Self::max_extent).
615    pub extent: f64,
616    /// The minimum value of [`extent`](Self::extent), which is >= 0.
617    pub min_extent: f64,
618    /// The maximum value of [`extent`](Self::extent).
619    pub max_extent: f64,
620    /// The initially requested value for [`extent`](Self::extent).
621    pub initial_extent: f64,
622    /// The build context of the widget that fired this notification.
623    ///
624    /// This can be used to find the sheet's render objects to determine the size
625    /// of the viewport, for instance. A listener can only assume this context
626    /// is live when it first gets the notification.
627    pub context: BuildContext,
628    /// Whether the widget that fired this notification, when dragged (or flung)
629    /// to the minimum extent, should cause its parent sheet to close.
630    ///
631    /// It is up to parent widgets to properly read and handle this value.
632    pub should_close_on_min_extent: bool,
633}
634
635impl DraggableScrollableNotification {
636    /// Creates a notification that the extent of a [`DraggableScrollableSheet`] has
637    /// changed; Dart's optional argument is the setter.
638    ///
639    /// Dart's default: `should_close_on_min_extent` true.
640    pub fn new(
641        extent: f64,
642        min_extent: f64,
643        max_extent: f64,
644        initial_extent: f64,
645        context: BuildContext,
646    ) -> DraggableScrollableNotification {
647        debug_assert!(0.0 <= min_extent);
648        debug_assert!(max_extent <= 1.0);
649        debug_assert!(min_extent <= extent);
650        debug_assert!(min_extent <= initial_extent);
651        debug_assert!(extent <= max_extent);
652        debug_assert!(initial_extent <= max_extent);
653        DraggableScrollableNotification {
654            viewport_notification: ViewportNotificationData::new(),
655            extent,
656            min_extent,
657            max_extent,
658            initial_extent,
659            context,
660            should_close_on_min_extent: true,
661        }
662    }
663
664    /// Dart `DraggableScrollableNotification(shouldCloseOnMinExtent:)`.
665    pub fn should_close_on_min_extent(
666        mut self,
667        should_close_on_min_extent: bool,
668    ) -> DraggableScrollableNotification {
669        self.should_close_on_min_extent = should_close_on_min_extent;
670        self
671    }
672}
673
674impl Notification for DraggableScrollableNotification {
675    fn as_any(&self) -> &dyn std::any::Any {
676        self
677    }
678
679    fn viewport_depth(&self) -> Option<&Cell<u32>> {
680        Some(self.viewport_notification.depth_cell())
681    }
682}
683
684impl ViewportNotificationMixin for DraggableScrollableNotification {
685    fn viewport_notification_data(&self) -> &ViewportNotificationData {
686        &self.viewport_notification
687    }
688}
689
690impl Debug for DraggableScrollableNotification {
691    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
692        let mut description = Vec::new();
693        ViewportNotificationMixin::debug_fill_description(self, &mut description);
694        description.push(format!(
695            "minExtent: {}, extent: {}, maxExtent: {}, initialExtent: {}",
696            self.min_extent, self.extent, self.max_extent, self.initial_extent
697        ));
698        write!(
699            f,
700            "DraggableScrollableNotification({})",
701            description.join(", ")
702        )
703    }
704}
705
706// ---------------------------------------------------------------------------------------------
707// _DraggableSheetExtent
708
709/// Manages state between [`DraggableScrollableSheetState`],
710/// [`DraggableScrollableSheetScrollController`], and
711/// [`DraggableScrollableSheetScrollPosition`]; Dart's `_DraggableSheetExtent`.
712///
713/// The state knows the pixels available along the axis the widget wants to
714/// scroll, but expects to get a fraction of those pixels to render the sheet.
715///
716/// The scroll position knows the number of pixels a user wants to move the sheet.
717///
718/// The [`available_pixels`](Self::available_pixels) may be `f64::INFINITY`.
719struct DraggableSheetExtent {
720    cancel_activity: Option<Listener>,
721    min_size: f64,
722    max_size: f64,
723    snap: bool,
724    snap_sizes: Vec<f64>,
725    snap_animation_duration: Option<Duration>,
726    initial_size: f64,
727    should_close_on_min_extent: bool,
728    current_size: Ref<ValueNotifier<f64>>,
729    available_pixels: f64,
730    // Used to disable snapping until the user has dragged on the sheet.
731    has_dragged: bool,
732    // Used to determine if the sheet should move to a new initial size when it
733    // changes.
734    // We need both `has_changed` and `has_dragged` to achieve the following
735    // behavior:
736    //   1. The sheet should only snap following user drags (as opposed to
737    //      programmatic sheet changes). See docs for `animate_to` and `jump_to`.
738    //   2. The sheet should move to a new initial child size on rebuild iff the
739    //      sheet has not changed, either by drag or programmatic control. See
740    //      docs for `initial_child_size`.
741    has_changed: bool,
742}
743
744impl DraggableSheetExtent {
745    #[allow(clippy::too_many_arguments)]
746    fn new(
747        app: &mut App,
748        min_size: f64,
749        max_size: f64,
750        snap: bool,
751        snap_sizes: Vec<f64>,
752        initial_size: f64,
753        snap_animation_duration: Option<Duration>,
754        current_size: Option<Ref<ValueNotifier<f64>>>,
755        has_dragged: Option<bool>,
756        has_changed: Option<bool>,
757        should_close_on_min_extent: bool,
758    ) -> Ref<DraggableSheetExtent> {
759        debug_assert!(min_size >= 0.0);
760        debug_assert!(max_size <= 1.0);
761        debug_assert!(min_size <= initial_size);
762        debug_assert!(initial_size <= max_size);
763        let current_size =
764            current_size.unwrap_or_else(|| app.create(ValueNotifier::new(initial_size)));
765        app.create(DraggableSheetExtent {
766            cancel_activity: None,
767            min_size,
768            max_size,
769            snap,
770            snap_sizes,
771            snap_animation_duration,
772            initial_size,
773            should_close_on_min_extent,
774            current_size,
775            available_pixels: f64::INFINITY,
776            has_dragged: has_dragged.unwrap_or(false),
777            has_changed: has_changed.unwrap_or(false),
778        })
779    }
780
781    /// The lowest fraction of the parent height the sheet may take.
782    pub fn min_size(self: Handle<Self>, app: &App) -> f64 {
783        app.get(self).min_size
784    }
785
786    /// The highest fraction of the parent height the sheet may take.
787    pub fn max_size(self: Handle<Self>, app: &App) -> f64 {
788        app.get(self).max_size
789    }
790
791    fn is_at_min(self: Handle<Self>, app: &App) -> bool {
792        app.get(self).min_size >= self.current_size(app)
793    }
794
795    fn is_at_max(self: Handle<Self>, app: &App) -> bool {
796        app.get(self).max_size <= self.current_size(app)
797    }
798
799    /// The fraction of the parent height the sheet currently takes.
800    pub fn current_size(self: Handle<Self>, app: &App) -> f64 {
801        *app.get(&app.get(self).current_size).value()
802    }
803
804    /// The pixel height the sheet currently takes.
805    pub fn current_pixels(self: Handle<Self>, app: &App) -> f64 {
806        self.size_to_pixels(app, self.current_size(app))
807    }
808
809    fn pixel_snap_sizes(self: Handle<Self>, app: &App) -> Vec<f64> {
810        app.get(self)
811            .snap_sizes
812            .clone()
813            .into_iter()
814            .map(|size| self.size_to_pixels(app, size))
815            .collect()
816    }
817
818    /// Start an activity that affects the sheet and register a cancel callback
819    /// that will be called if another activity starts.
820    ///
821    /// The `on_canceled` callback will get called even if the subsequent activity
822    /// started after this one finished, so `on_canceled` must be safe to call at
823    /// any time.
824    fn start_activity(self: Handle<Self>, app: &mut App, on_canceled: Listener) {
825        if let Some(cancel_activity) = app.get(self).cancel_activity.clone() {
826            cancel_activity.call(app);
827        }
828        app.get_mut(self).cancel_activity = Some(on_canceled);
829    }
830
831    /// The scroll position gets inputs in terms of pixels, but the size is
832    /// expected to be expressed as a number between 0..1.
833    ///
834    /// This should only be called to respond to a user drag. To update the
835    /// size in response to a programmatic call, use [`update_size`](Self::update_size)
836    /// directly.
837    fn add_pixel_delta(self: Handle<Self>, app: &mut App, delta: f64, context: BuildContext) {
838        // Stop any playing sheet animations.
839        if let Some(cancel_activity) = app.get_mut(self).cancel_activity.take() {
840            cancel_activity.call(app);
841        }
842        // The user has interacted with the sheet, set `has_dragged` to true so that
843        // we'll snap if applicable.
844        app.get_mut(self).has_dragged = true;
845        app.get_mut(self).has_changed = true;
846        if app.get(self).available_pixels == 0.0 {
847            return;
848        }
849        let new_size = self.current_size(app) + self.pixels_to_size(app, delta);
850        self.update_size(app, new_size, context);
851    }
852
853    /// Set the size to the new value. `new_size` should be a number between
854    /// [`min_size`](Self::min_size) and [`max_size`](Self::max_size).
855    ///
856    /// This can be triggered by a programmatic (e.g. controller triggered) change
857    /// or a user drag.
858    fn update_size(self: Handle<Self>, app: &mut App, new_size: f64, context: BuildContext) {
859        let clamped_size = clamp_double(new_size, app.get(self).min_size, app.get(self).max_size);
860        if self.current_size(app) == clamped_size {
861            return;
862        }
863        let current_size = app.get(self).current_size.handle();
864        current_size.set_value(app, clamped_size);
865        let extent = app.get(self);
866        DraggableScrollableNotification::new(
867            self.current_size(app),
868            extent.min_size,
869            extent.max_size,
870            extent.initial_size,
871            context,
872        )
873        .should_close_on_min_extent(extent.should_close_on_min_extent)
874        .dispatch(app, Some(context));
875    }
876
877    /// Converts a pixel height to a fraction of the parent container's height.
878    pub fn pixels_to_size(self: Handle<Self>, app: &App, pixels: f64) -> f64 {
879        let extent = app.get(self);
880        pixels / extent.available_pixels * extent.max_size
881    }
882
883    /// Converts a fraction of the parent container's height to a pixel height.
884    pub fn size_to_pixels(self: Handle<Self>, app: &App, size: f64) -> f64 {
885        let extent = app.get(self);
886        size / extent.max_size * extent.available_pixels
887    }
888
889    /// Discards any resources used by the object.
890    pub fn dispose(self: Handle<Self>, app: &mut App) {
891        let current_size = app.get(self).current_size.handle();
892        current_size.dispose(app);
893    }
894
895    #[allow(clippy::too_many_arguments)]
896    fn copy_with(
897        self: Handle<Self>,
898        app: &mut App,
899        min_size: f64,
900        max_size: f64,
901        snap: bool,
902        snap_sizes: Vec<f64>,
903        initial_size: f64,
904        snap_animation_duration: Option<Duration>,
905        should_close_on_min_extent: bool,
906    ) -> Ref<DraggableSheetExtent> {
907        let has_changed = app.get(self).has_changed;
908        let has_dragged = app.get(self).has_dragged;
909        // Set the current size to the possibly updated initial size if the sheet
910        // hasn't changed yet.
911        let size = if has_changed {
912            clamp_double(self.current_size(app), min_size, max_size)
913        } else {
914            initial_size
915        };
916        let current_size = app.create(ValueNotifier::new(size));
917        DraggableSheetExtent::new(
918            app,
919            min_size,
920            max_size,
921            snap,
922            snap_sizes,
923            initial_size,
924            snap_animation_duration,
925            Some(current_size),
926            Some(has_dragged),
927            Some(has_changed),
928            should_close_on_min_extent,
929        )
930    }
931}
932
933impl Debug for DraggableSheetExtent {
934    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
935        f.debug_struct("DraggableSheetExtent")
936            .field("minSize", &self.min_size)
937            .field("maxSize", &self.max_size)
938            .field("snap", &self.snap)
939            .finish_non_exhaustive()
940    }
941}
942
943// ---------------------------------------------------------------------------------------------
944// _DraggableScrollableSheetState
945
946/// Dart's `_DraggableScrollableSheetState`.
947pub struct DraggableScrollableSheetState {
948    state: StateData<DraggableScrollableSheet>,
949    scroll_controller: Option<Ref<DraggableScrollableSheetScrollController>>,
950    extent: Option<Ref<DraggableSheetExtent>>,
951}
952
953impl DraggableScrollableSheetState {
954    fn scroll_controller(
955        self: Handle<Self>,
956        app: &App,
957    ) -> Handle<DraggableScrollableSheetScrollController> {
958        app.get(self)
959            .scroll_controller
960            .handle()
961            .expect("init_state has run")
962    }
963
964    fn extent(self: Handle<Self>, app: &App) -> Handle<DraggableSheetExtent> {
965        app.get(self).extent.handle().expect("init_state has run")
966    }
967
968    fn implied_snap_sizes(self: Handle<Self>, app: &App) -> Vec<f64> {
969        let widget = self.widget(app);
970        if cfg!(debug_assertions)
971            && let Some(snap_sizes) = &widget.snap_sizes
972        {
973            for (index, snap_size) in snap_sizes.iter().copied().enumerate() {
974                debug_assert!(
975                    snap_size >= widget.min_child_size && snap_size <= widget.max_child_size,
976                    "Invalid snapSize '{snap_size}' at index {index}. Snap sizes must be \
977                     between `minChildSize` and `maxChildSize`."
978                );
979                debug_assert!(
980                    index == 0 || snap_size > snap_sizes[index - 1],
981                    "Invalid snapSize '{snap_size}' at index {index}. Snap sizes must be in \
982                     ascending order."
983                );
984            }
985        }
986        // Ensure the snap sizes start and end with the min and max child sizes.
987        let Some(snap_sizes) = widget.snap_sizes.as_ref().filter(|sizes| !sizes.is_empty()) else {
988            return vec![widget.min_child_size, widget.max_child_size];
989        };
990        let mut implied = Vec::with_capacity(snap_sizes.len() + 2);
991        if snap_sizes[0] != widget.min_child_size {
992            implied.push(widget.min_child_size);
993        }
994        implied.extend_from_slice(snap_sizes);
995        if snap_sizes[snap_sizes.len() - 1] != widget.max_child_size {
996            implied.push(widget.max_child_size);
997        }
998        implied
999    }
1000
1001    fn replace_extent(self: Handle<Self>, app: &mut App, old_widget: &DraggableScrollableSheet) {
1002        let previous_extent = self.extent(app);
1003        let snap_sizes = self.implied_snap_sizes(app);
1004        let widget = self.widget(app);
1005        let (min, max, snap, duration, initial, close_on_min) = (
1006            widget.min_child_size,
1007            widget.max_child_size,
1008            widget.snap,
1009            widget.snap_animation_duration,
1010            widget.initial_child_size,
1011            widget.should_close_on_min_extent,
1012        );
1013        let snap_sizes_changed = widget.snap_sizes != old_widget.snap_sizes;
1014        let snap_changed = widget.snap != old_widget.snap;
1015        let extent = previous_extent.copy_with(
1016            app,
1017            min,
1018            max,
1019            snap,
1020            snap_sizes,
1021            initial,
1022            duration,
1023            close_on_min,
1024        );
1025        app.get_mut(self).extent = Some(extent.clone());
1026        // Modify the existing scroll controller instead of replacing it so that
1027        // developers listening to the controller do not have to rebuild their listeners.
1028        let scroll_controller = self.scroll_controller(app);
1029        app.get_mut(scroll_controller).extent = extent;
1030        // If an external facing controller was provided, let it know that the
1031        // extent has been replaced.
1032        if let Some(controller) = self.widget(app).controller.handle() {
1033            controller.on_extent_replaced(app, previous_extent);
1034        }
1035        previous_extent.dispose(app);
1036        if snap && (snap_changed || snap_sizes_changed) && scroll_controller.has_clients(app) {
1037            // Trigger a snap in case snap or snapSizes has changed and there is a
1038            // scroll position currently attached. We put this in a post frame
1039            // callback so that `build` can update `extent.available_pixels` before
1040            // this runs — we can't use the previous extent's available pixels as it may
1041            // have changed when the widget was updated.
1042            let scroll_controller = app
1043                .get(self)
1044                .scroll_controller
1045                .clone()
1046                .expect("init_state has run");
1047            SchedulerBinding::add_post_frame_callback(
1048                app,
1049                FrameCallback::new(move |app, _timestamp| {
1050                    for position in scroll_controller.positions(app) {
1051                        let position = position
1052                            .downcast::<DraggableScrollableSheetScrollPosition>(app)
1053                            .expect("the controller creates its own positions");
1054                        ScrollActivityDelegate::go_ballistic(position, app, 0.0);
1055                    }
1056                }),
1057                View::maybe_id_of(app, self.context(app)),
1058            );
1059        }
1060    }
1061}
1062
1063impl State for DraggableScrollableSheetState {
1064    type Widget = DraggableScrollableSheet;
1065    crate::state_accessors!();
1066
1067    fn init_state(self: Handle<Self>, app: &mut App) {
1068        let snap_sizes = self.implied_snap_sizes(app);
1069        let widget = self.widget(app);
1070        let (min, max, snap, duration, initial, close_on_min) = (
1071            widget.min_child_size,
1072            widget.max_child_size,
1073            widget.snap,
1074            widget.snap_animation_duration,
1075            widget.initial_child_size,
1076            widget.should_close_on_min_extent,
1077        );
1078        let extent = DraggableSheetExtent::new(
1079            app,
1080            min,
1081            max,
1082            snap,
1083            snap_sizes,
1084            initial,
1085            duration,
1086            None,
1087            None,
1088            None,
1089            close_on_min,
1090        );
1091        app.get_mut(self).extent = Some(extent.clone());
1092        let scroll_controller = DraggableScrollableSheetScrollController::new(app, extent);
1093        app.get_mut(self).scroll_controller = Some(scroll_controller.clone());
1094        if let Some(controller) = self.widget(app).controller.handle() {
1095            controller.attach(app, scroll_controller);
1096        }
1097    }
1098
1099    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &DraggableScrollableSheet) {
1100        let controller = self.widget(app).controller.handle();
1101        if controller != old_widget.controller.handle() {
1102            if let Some(old_controller) = old_widget.controller.handle() {
1103                old_controller.detach(app, false);
1104            }
1105            if let Some(controller) = controller {
1106                let scroll_controller = app
1107                    .get(self)
1108                    .scroll_controller
1109                    .clone()
1110                    .expect("init_state has run");
1111                controller.attach(app, scroll_controller);
1112            }
1113        }
1114        self.replace_extent(app, old_widget);
1115    }
1116
1117    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1118        let context = self.context(app);
1119        if InheritedResetNotifier::should_reset(app, context) {
1120            self.scroll_controller(app).reset(app);
1121        }
1122    }
1123
1124    fn dispose(self: Handle<Self>, app: &mut App) {
1125        match self.widget(app).controller.handle() {
1126            None => self.extent(app).dispose(app),
1127            Some(controller) => controller.detach(app, true),
1128        }
1129        self.scroll_controller(app).dispose(app);
1130    }
1131
1132    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1133        let extent = self.extent(app);
1134        let expand = self.widget(app).expand;
1135        let max_child_size = self.widget(app).max_child_size;
1136        let builder = Rc::clone(&self.widget(app).builder);
1137        let scroll_controller = app
1138            .get(self)
1139            .scroll_controller
1140            .clone()
1141            .expect("init_state has run");
1142        let child = builder(app, context, scroll_controller.into_erased());
1143        let current_size: Rc<dyn ValueListenable<f64>> =
1144            Rc::new(app.get(extent).current_size.clone());
1145        ValueListenableBuilder::<f64>::new(
1146            current_size,
1147            move |_app, _context, current_size, child| {
1148                let current_size = *current_size;
1149                let child = child.cloned();
1150                LayoutBuilder::new(move |app, _context, constraints| {
1151                    // Dart's `_extent`, read through the state when the layout runs.
1152                    let extent = self.extent(app);
1153                    app.get_mut(extent).available_pixels =
1154                        max_child_size * constraints.biggest().height();
1155                    let mut sheet = FractionallySizedBox::new()
1156                        .height_factor(current_size)
1157                        .alignment(AlignmentGeometry::BOTTOM_CENTER);
1158                    if let Some(child) = &child {
1159                        sheet = sheet.child(child.clone());
1160                    }
1161                    if expand {
1162                        SizedBox::expand().child(sheet).into_widget()
1163                    } else {
1164                        sheet.into_widget()
1165                    }
1166                })
1167                .into_widget()
1168            },
1169        )
1170        .child(child)
1171        .into_widget()
1172    }
1173}
1174
1175// ---------------------------------------------------------------------------------------------
1176// _DraggableScrollableSheetScrollController
1177
1178/// A `ScrollController` suitable for use in a [`ScrollableWidgetBuilder`] created
1179/// by a [`DraggableScrollableSheet`]; Dart's `_DraggableScrollableSheetScrollController`.
1180///
1181/// If a [`DraggableScrollableSheet`] contains content that exceeds the height
1182/// of its container, this controller will allow the sheet to both be dragged to
1183/// fill the container and then scroll the child content.
1184///
1185/// See also:
1186///
1187///  * [`DraggableScrollableSheetScrollPosition`], which manages the positioning logic for
1188///    this controller.
1189///  * `PrimaryScrollController`, which can be used to establish this controller as the
1190///    primary controller for descendants.
1191struct DraggableScrollableSheetScrollController {
1192    change_notifier: ChangeNotifierData,
1193    scroll_controller: ScrollControllerData,
1194    extent: Ref<DraggableSheetExtent>,
1195    on_position_detached: Option<Listener>,
1196}
1197
1198impl DraggableScrollableSheetScrollController {
1199    fn new(
1200        app: &mut App,
1201        extent: Ref<DraggableSheetExtent>,
1202    ) -> Ref<DraggableScrollableSheetScrollController> {
1203        app.create(DraggableScrollableSheetScrollController {
1204            change_notifier: ChangeNotifierData::new(),
1205            scroll_controller: ScrollControllerData::new(0.0, true, None, None, None),
1206            extent,
1207            on_position_detached: None,
1208        })
1209    }
1210
1211    /// Dart's `_DraggableScrollableSheetScrollController.position`, which narrows
1212    /// `ScrollController.position` to the position this controller creates.
1213    pub fn position(
1214        self: Handle<Self>,
1215        app: &App,
1216    ) -> Handle<DraggableScrollableSheetScrollPosition> {
1217        ScrollControllerLeaf::position(self, app)
1218            .downcast::<DraggableScrollableSheetScrollPosition>(app)
1219            .expect("the controller creates its own positions")
1220    }
1221
1222    fn reset(self: Handle<Self>, app: &mut App) {
1223        let extent = app.get(self).extent.handle();
1224        if let Some(cancel_activity) = app.get(extent).cancel_activity.clone() {
1225            cancel_activity.call(app);
1226        }
1227        app.get_mut(extent).has_dragged = false;
1228        app.get_mut(extent).has_changed = false;
1229        // `jump_to` can result in trying to replace semantics during build.
1230        // Just animate really fast.
1231        // Avoid doing it at all if the offset is already 0.0.
1232        if self.offset(app) != 0.0 {
1233            self.animate_to(
1234                app,
1235                0.0,
1236                Duration::from_millis(1),
1237                waft_animation::Curves::linear(),
1238            );
1239        }
1240        let initial_size = app.get(extent).initial_size;
1241        let context = self.position(app).context(app).notification_context(app);
1242        extent.update_size(app, initial_size, context.expect("a mounted scrollable"));
1243    }
1244}
1245
1246impl ChangeNotifier for DraggableScrollableSheetScrollController {
1247    fn change_notifier_data(&self) -> &ChangeNotifierData {
1248        &self.change_notifier
1249    }
1250
1251    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1252        &mut self.change_notifier
1253    }
1254}
1255
1256impl ScrollControllerLeaf for DraggableScrollableSheetScrollController {
1257    crate::scroll_controller_accessors!();
1258
1259    fn create_scroll_position(
1260        self: Handle<Self>,
1261        app: &mut App,
1262        physics: ScrollPhysicsRef,
1263        context: Rc<dyn ScrollContext>,
1264        old_position: Option<AnyScrollPosition>,
1265    ) -> ScrollPositionRef {
1266        let physics = physics.apply_to(Some(Rc::new(AlwaysScrollableScrollPhysics::new())));
1267        DraggableScrollableSheetScrollPosition::new(
1268            app,
1269            physics,
1270            context,
1271            old_position,
1272            Rc::new(move |app: &App| app.get(self).extent.handle()),
1273        )
1274        .into_erased()
1275    }
1276
1277    fn debug_fill_description(self: Handle<Self>, app: &App, description: &mut Vec<String>) {
1278        ScrollController::debug_fill_description(self.as_controller(), app, description);
1279        description.push(format!("extent: {:?}", app.get(self).extent));
1280    }
1281
1282    fn detach(self: Handle<Self>, app: &mut App, position: AnyScrollPosition) {
1283        if let Some(on_position_detached) = app.get(self).on_position_detached.clone() {
1284            on_position_detached.call(app);
1285        }
1286        ScrollController::detach(self.as_controller(), app, position);
1287    }
1288}
1289
1290// ---------------------------------------------------------------------------------------------
1291// _DraggableScrollableSheetScrollPosition
1292
1293/// A scroll position that manages scroll activities for
1294/// [`DraggableScrollableSheetScrollController`]; Dart's
1295/// `_DraggableScrollableSheetScrollPosition`.
1296///
1297/// This is a [`ScrollPositionWithSingleContextLeaf`] whose activities change the
1298/// sheet's current size or the visible content offset in the `Scrollable`'s `Viewport`.
1299struct DraggableScrollableSheetScrollPosition {
1300    change_notifier: ChangeNotifierData,
1301    scroll_position: ScrollPositionData,
1302    single_context: ScrollPositionWithSingleContextData,
1303    drag_cancel_callback: Option<Listener>,
1304    get_extent: GetSheetExtent,
1305    ballistic_controllers: Vec<Ref<AnimationController>>,
1306}
1307
1308impl DraggableScrollableSheetScrollPosition {
1309    fn new(
1310        app: &mut App,
1311        physics: ScrollPhysicsRef,
1312        context: Rc<dyn ScrollContext>,
1313        old_position: Option<AnyScrollPosition>,
1314        get_extent: GetSheetExtent,
1315    ) -> Ref<DraggableScrollableSheetScrollPosition> {
1316        let scroll_position = ScrollPositionData::new(app, physics, context, true, None);
1317        let this = app.create(DraggableScrollableSheetScrollPosition {
1318            change_notifier: ChangeNotifierData::new(),
1319            scroll_position,
1320            single_context: ScrollPositionWithSingleContextData::new(),
1321            drag_cancel_callback: None,
1322            get_extent,
1323            ballistic_controllers: Vec::new(),
1324        });
1325        ScrollPositionWithSingleContext::init(this.handle(), app, Some(0.0), old_position);
1326        this
1327    }
1328
1329    /// Whether the list scrolls rather than the sheet resizing.
1330    pub fn list_should_scroll(self: Handle<Self>, app: &App) -> bool {
1331        waft_rendering::ViewportOffset::pixels(self, app) > 0.0
1332    }
1333
1334    /// The sheet's shared extent.
1335    pub fn extent(self: Handle<Self>, app: &App) -> Handle<DraggableSheetExtent> {
1336        (Rc::clone(&app.get(self).get_extent))(app)
1337    }
1338
1339    // Checks if the sheet's current size is close to a snap size, returning the
1340    // snap size if so; returns `None` otherwise.
1341    fn get_current_snap_size(self: Handle<Self>, app: &App) -> Option<f64> {
1342        let extent = self.extent(app);
1343        let metrics = self.copy_with(app);
1344        let tolerance = self.physics(app).tolerance_for(&*metrics).distance;
1345        let current_size = extent.current_size(app);
1346        app.get(extent)
1347            .snap_sizes
1348            .iter()
1349            .copied()
1350            .find(|snap_size| {
1351                (current_size - snap_size).abs() <= extent.pixels_to_size(app, tolerance)
1352            })
1353    }
1354
1355    fn is_at_snap_size(self: Handle<Self>, app: &App) -> bool {
1356        self.get_current_snap_size(app).is_some()
1357    }
1358
1359    fn should_snap(self: Handle<Self>, app: &App) -> bool {
1360        let extent = self.extent(app);
1361        app.get(extent).snap && app.get(extent).has_dragged && !self.is_at_snap_size(app)
1362    }
1363}
1364
1365impl ChangeNotifier for DraggableScrollableSheetScrollPosition {
1366    fn change_notifier_data(&self) -> &ChangeNotifierData {
1367        &self.change_notifier
1368    }
1369
1370    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1371        &mut self.change_notifier
1372    }
1373}
1374
1375impl waft_rendering::ViewportOffset for DraggableScrollableSheetScrollPosition {
1376    crate::scroll_position_with_single_context_viewport_offset_overrides!();
1377}
1378
1379impl ScrollPosition for DraggableScrollableSheetScrollPosition {
1380    crate::scroll_position_with_single_context_overrides!();
1381}
1382
1383impl ScrollActivityDelegate for DraggableScrollableSheetScrollPosition {
1384    crate::scroll_position_with_single_context_delegate_overrides!();
1385}
1386
1387impl ScrollPositionWithSingleContextLeaf for DraggableScrollableSheetScrollPosition {
1388    crate::scroll_position_with_single_context_accessors!();
1389
1390    fn absorb(self: Handle<Self>, app: &mut App, other: AnyScrollPosition) {
1391        ScrollPositionWithSingleContext::absorb(self, app, other);
1392        debug_assert!(app.get(self).drag_cancel_callback.is_none());
1393
1394        let Some(other) = other.downcast::<DraggableScrollableSheetScrollPosition>(app) else {
1395            return;
1396        };
1397
1398        if let Some(drag_cancel_callback) = app.get_mut(other).drag_cancel_callback.take() {
1399            app.get_mut(self).drag_cancel_callback = Some(drag_cancel_callback);
1400        }
1401    }
1402
1403    fn begin_activity(self: Handle<Self>, app: &mut App, new_activity: Option<ScrollActivityRef>) {
1404        // Cancel the running ballistic simulations
1405        for ballistic_controller in app.get(self).ballistic_controllers.clone() {
1406            ballistic_controller.stop(app, true);
1407        }
1408        ScrollPositionWithSingleContext::begin_activity(self, app, new_activity);
1409    }
1410
1411    fn apply_user_offset(self: Handle<Self>, app: &mut App, delta: f64) {
1412        let extent = self.extent(app);
1413        let is_at_min = extent.is_at_min(app);
1414        let is_at_max = extent.is_at_max(app);
1415        if !self.list_should_scroll(app)
1416            && (!(is_at_min || is_at_max)
1417                || (is_at_min && delta < 0.0)
1418                || (is_at_max && delta > 0.0))
1419        {
1420            let context = self.context(app).notification_context(app);
1421            extent.add_pixel_delta(app, -delta, context.expect("a mounted scrollable"));
1422        } else {
1423            ScrollPositionWithSingleContext::apply_user_offset(self, app, delta);
1424        }
1425    }
1426
1427    fn dispose(self: Handle<Self>, app: &mut App) {
1428        for ballistic_controller in std::mem::take(&mut app.get_mut(self).ballistic_controllers) {
1429            ballistic_controller.dispose(app);
1430        }
1431        ScrollPositionWithSingleContext::dispose(self, app);
1432    }
1433
1434    fn go_ballistic(self: Handle<Self>, app: &mut App, velocity: f64) {
1435        let extent = self.extent(app);
1436        if (velocity == 0.0 && !self.should_snap(app))
1437            || (velocity < 0.0 && self.list_should_scroll(app))
1438            || (velocity > 0.0 && extent.is_at_max(app))
1439        {
1440            ScrollPositionWithSingleContext::go_ballistic(self, app, velocity);
1441            return;
1442        }
1443        // Scrollable expects that we will dispose of its current drag cancel callback.
1444        if let Some(drag_cancel_callback) = app.get_mut(self).drag_cancel_callback.take() {
1445            drag_cancel_callback.call(app);
1446        }
1447
1448        let metrics = self.copy_with(app);
1449        let tolerance = self.physics(app).tolerance_for(&*metrics);
1450        let simulation: Box<dyn Simulation> = if app.get(extent).snap {
1451            // Snap is enabled, simulate snapping instead of clamping scroll.
1452            Box::new(SnappingSimulation::new(
1453                extent.current_pixels(app),
1454                velocity,
1455                extent.pixel_snap_sizes(app),
1456                app.get(extent).snap_animation_duration,
1457                tolerance,
1458            ))
1459        } else {
1460            // The iOS bouncing simulation just isn't right here - once we delegate
1461            // the ballistic back to the ScrollView, it will use the right simulation.
1462            Box::new(ClampingScrollSimulation::with_options(
1463                // Run the simulation in terms of pixels, not extent.
1464                extent.current_pixels(app),
1465                velocity,
1466                ClampingScrollSimulation::DEFAULT_FRICTION,
1467                tolerance,
1468            ))
1469        };
1470
1471        let vsync = self.context(app).vsync();
1472        let ballistic_controller = AnimationController::unbounded(
1473            app,
1474            0.0,
1475            None,
1476            None,
1477            AnimationBehavior::Preserve,
1478            vsync,
1479        );
1480        app.get_mut(self)
1481            .ballistic_controllers
1482            .push(ballistic_controller.clone());
1483        let ballistic_controller = ballistic_controller.handle();
1484
1485        let last_position = Rc::new(Cell::new(extent.current_pixels(app)));
1486        let velocity = Rc::new(Cell::new(velocity));
1487        let tick = {
1488            let last_position = Rc::clone(&last_position);
1489            let velocity = Rc::clone(&velocity);
1490            move |app: &mut App| {
1491                let value = ballistic_controller.value(app);
1492                let delta = value - last_position.get();
1493                last_position.set(value);
1494                let context = self.context(app).notification_context(app);
1495                // Dart's `extent` getter, read when the tick runs.
1496                let extent = self.extent(app);
1497                extent.add_pixel_delta(app, delta, context.expect("a mounted scrollable"));
1498                if (velocity.get() > 0.0 && extent.is_at_max(app))
1499                    || (velocity.get() < 0.0 && extent.is_at_min(app))
1500                {
1501                    // Make sure we pass along enough velocity to keep scrolling - otherwise
1502                    // we just "bounce" off the top making it look like the list doesn't
1503                    // have more to scroll.
1504                    let controller_velocity = ballistic_controller.velocity(app);
1505                    let metrics = self.copy_with(app);
1506                    velocity.set(
1507                        controller_velocity
1508                            + self.physics(app).tolerance_for(&*metrics).velocity
1509                                * controller_velocity.signum(),
1510                    );
1511                    ScrollPositionWithSingleContext::go_ballistic(self, app, velocity.get());
1512                    ballistic_controller.stop(app, true);
1513                } else if Animation::is_completed(ballistic_controller, app) {
1514                    // Update the extent value after the snap animation completes to
1515                    // avoid rounding errors that could prevent the sheet from closing when
1516                    // it reaches minSize.
1517                    if let Some(snap_size) = self.get_current_snap_size(app) {
1518                        let context = self.context(app).notification_context(app);
1519                        self.extent(app).update_size(
1520                            app,
1521                            snap_size,
1522                            context.expect("a mounted scrollable"),
1523                        );
1524                    }
1525                    ScrollPositionWithSingleContext::go_ballistic(self, app, 0.0);
1526                }
1527            }
1528        };
1529
1530        Animation::add_listener(ballistic_controller, app, Listener::new(tick));
1531        let future = ballistic_controller.animate_with(app, simulation);
1532        future.when_complete_or_cancel(
1533            app,
1534            Listener::new(move |app: &mut App| {
1535                let controllers = &mut app.get_mut(self).ballistic_controllers;
1536                if let Some(index) = controllers
1537                    .iter()
1538                    .position(|controller| controller == ballistic_controller)
1539                {
1540                    let removed = controllers.remove(index);
1541                    removed.dispose(app);
1542                }
1543            }),
1544        );
1545    }
1546
1547    fn drag(
1548        self: Handle<Self>,
1549        app: &mut App,
1550        details: DragStartDetails,
1551        drag_cancel_callback: Listener,
1552    ) -> Rc<dyn Drag> {
1553        // Save this so we can call it later if we have to `go_ballistic` on our own.
1554        app.get_mut(self).drag_cancel_callback = Some(drag_cancel_callback.clone());
1555        ScrollPositionWithSingleContext::drag(self, app, details, drag_cancel_callback)
1556    }
1557}
1558
1559// ---------------------------------------------------------------------------------------------
1560// DraggableScrollableActuator
1561
1562/// A widget that can notify a descendent [`DraggableScrollableSheet`] that it
1563/// should reset its position to the initial state.
1564///
1565/// This is just a wrapper on top of [`DraggableScrollableController`]. It is
1566/// primarily useful for controlling a sheet in a part of the widget tree that
1567/// the current code does not control (e.g. library code trying to affect a sheet
1568/// in library users' code). Generally, it's easier to control the sheet
1569/// directly by creating a controller and passing the controller to the sheet in
1570/// its constructor (see [`DraggableScrollableSheet::controller`]).
1571#[derive(Debug)]
1572pub struct DraggableScrollableActuator {
1573    /// See `Widget::key`.
1574    pub key: Option<KeyRef>,
1575    /// This child's [`DraggableScrollableSheet`] descendant will be reset when the
1576    /// [`reset`](Self::reset) method is applied to a context that includes it.
1577    pub child: WidgetRef,
1578}
1579
1580impl DraggableScrollableActuator {
1581    /// Creates a widget that can notify descendent [`DraggableScrollableSheet`]s
1582    /// to reset to their initial position.
1583    #[cfg_attr(debug_assertions, track_caller)]
1584    pub fn new<K>(child: impl IntoWidget<K>) -> DraggableScrollableActuator {
1585        DraggableScrollableActuator {
1586            key: None,
1587            child: child.into_widget(),
1588        }
1589    }
1590
1591    /// Dart `DraggableScrollableActuator(key:)`.
1592    pub fn key(mut self, key: KeyRef) -> DraggableScrollableActuator {
1593        self.key = Some(key);
1594        self
1595    }
1596
1597    /// Notifies any descendant [`DraggableScrollableSheet`] that it should reset
1598    /// to its initial position.
1599    ///
1600    /// Returns `true` if a [`DraggableScrollableActuator`] is available and
1601    /// some [`DraggableScrollableSheet`] is listening for updates, `false`
1602    /// otherwise.
1603    pub fn reset(app: &mut App, context: BuildContext) -> bool {
1604        let notifier = context
1605            .depend_on_inherited_widget_of_exact_type::<InheritedResetNotifier>(app)
1606            .map(|widget| widget.notifier.handle());
1607        notifier.is_some_and(|notifier| notifier.send_reset(app))
1608    }
1609}
1610
1611impl StatefulWidget for DraggableScrollableActuator {
1612    type State = DraggableScrollableActuatorState;
1613
1614    fn key(&self) -> Option<&KeyRef> {
1615        self.key.as_ref()
1616    }
1617
1618    fn create_state(&self) -> DraggableScrollableActuatorState {
1619        DraggableScrollableActuatorState {
1620            state: StateData::new(),
1621            notifier: None,
1622        }
1623    }
1624}
1625
1626/// Dart's `_DraggableScrollableActuatorState`.
1627pub struct DraggableScrollableActuatorState {
1628    state: StateData<DraggableScrollableActuator>,
1629    notifier: Option<Ref<ResetNotifier>>,
1630}
1631
1632impl State for DraggableScrollableActuatorState {
1633    type Widget = DraggableScrollableActuator;
1634    crate::state_accessors!();
1635
1636    fn init_state(self: Handle<Self>, app: &mut App) {
1637        app.get_mut(self).notifier = Some(ResetNotifier::new(app));
1638    }
1639
1640    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1641        InheritedResetNotifier {
1642            notifier: app.get(self).notifier.clone().expect("init_state has run"),
1643            child: self.widget(app).child.clone(),
1644        }
1645        .into_widget()
1646    }
1647
1648    fn dispose(self: Handle<Self>, app: &mut App) {
1649        let notifier = app.get(self).notifier.handle().expect("init_state has run");
1650        notifier.dispose(app);
1651    }
1652}
1653
1654/// A `ChangeNotifier` to use with `_InheritedResetNotifier` to notify
1655/// descendants that they should reset to initial state; Dart's `_ResetNotifier`.
1656struct ResetNotifier {
1657    change_notifier: ChangeNotifierData,
1658    /// Whether someone called [`send_reset`](Self::send_reset) or not.
1659    ///
1660    /// This flag is reset after checking it.
1661    was_called: bool,
1662}
1663
1664impl ResetNotifier {
1665    fn new(app: &mut App) -> Ref<ResetNotifier> {
1666        app.create(ResetNotifier {
1667            change_notifier: ChangeNotifierData::new(),
1668            was_called: false,
1669        })
1670    }
1671
1672    /// Fires a reset notification to descendants.
1673    ///
1674    /// Returns false if there are no listeners.
1675    fn send_reset(self: Handle<Self>, app: &mut App) -> bool {
1676        if !app.get(self).change_notifier.has_listeners() {
1677            return false;
1678        }
1679        app.get_mut(self).was_called = true;
1680        self.notify_listeners(app);
1681        true
1682    }
1683
1684    /// Discards any resources used by the object.
1685    fn dispose(self: Handle<Self>, app: &mut App) {
1686        ChangeNotifierData::dispose(app, self);
1687    }
1688}
1689
1690impl ChangeNotifier for ResetNotifier {
1691    fn change_notifier_data(&self) -> &ChangeNotifierData {
1692        &self.change_notifier
1693    }
1694
1695    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
1696        &mut self.change_notifier
1697    }
1698}
1699
1700/// An [`InheritedNotifier`] that a [`DraggableScrollableSheet`] listens to for an indication
1701/// that it should reset itself back to [`DraggableScrollableSheet::initial_child_size`];
1702/// Dart's `_InheritedResetNotifier`.
1703#[derive(Debug)]
1704struct InheritedResetNotifier {
1705    notifier: Ref<ResetNotifier>,
1706    child: WidgetRef,
1707}
1708
1709impl InheritedResetNotifier {
1710    /// The tree node; both [`InheritedWidget`] and [`InheritedNotifier`] offer an
1711    /// `IntoWidget` kind, so this widget names the conversion itself.
1712    fn into_widget(self) -> WidgetRef {
1713        IntoWidget::<InheritedNotifierKind>::into_widget(self)
1714    }
1715
1716    /// Specifies whether the [`DraggableScrollableSheet`] should reset to its
1717    /// initial position.
1718    ///
1719    /// Returns true if the notifier requested a reset, false otherwise.
1720    fn should_reset(app: &mut App, context: BuildContext) -> bool {
1721        let Some(widget) =
1722            context.depend_on_inherited_widget_of_exact_type::<InheritedResetNotifier>(app)
1723        else {
1724            return false;
1725        };
1726        let notifier = widget.notifier.handle();
1727        let was_called = app.get(notifier).was_called;
1728        app.get_mut(notifier).was_called = false;
1729        was_called
1730    }
1731}
1732
1733impl InheritedWidget for InheritedResetNotifier {
1734    crate::inherited_notifier_overrides!();
1735
1736    fn child(&self) -> &WidgetRef {
1737        &self.child
1738    }
1739}
1740
1741impl InheritedNotifier for InheritedResetNotifier {
1742    type Notifier = ResetNotifier;
1743
1744    fn notifier(&self) -> Option<Handle<ResetNotifier>> {
1745        Some(self.notifier.handle())
1746    }
1747}
1748
1749// ---------------------------------------------------------------------------------------------
1750// _SnappingSimulation
1751
1752/// Dart's `_SnappingSimulation`: settles the sheet on the snap size the drag is headed for.
1753#[derive(Debug)]
1754struct SnappingSimulation {
1755    position: f64,
1756    velocity: f64,
1757    pixel_snap_size: f64,
1758    tolerance: Tolerance,
1759}
1760
1761impl SnappingSimulation {
1762    // A minimum speed to snap at. Used to ensure that the snapping animation
1763    // does not play too slowly.
1764    const MINIMUM_SPEED: f64 = 1600.0;
1765
1766    fn new(
1767        position: f64,
1768        initial_velocity: f64,
1769        pixel_snap_size: Vec<f64>,
1770        snap_animation_duration: Option<Duration>,
1771        tolerance: Tolerance,
1772    ) -> SnappingSimulation {
1773        let pixel_snap_size = SnappingSimulation::get_snap_size(
1774            position,
1775            initial_velocity,
1776            &pixel_snap_size,
1777            tolerance,
1778        );
1779
1780        let velocity = match snap_animation_duration {
1781            Some(duration) if duration.as_millis() > 0 => {
1782                (pixel_snap_size - position) * 1000.0 / duration.as_millis() as f64
1783            }
1784            // Check the direction of the target instead of the sign of the velocity because
1785            // we may snap in the opposite direction of velocity if velocity is very low.
1786            _ if pixel_snap_size < position => {
1787                (-SnappingSimulation::MINIMUM_SPEED).min(initial_velocity)
1788            }
1789            _ => SnappingSimulation::MINIMUM_SPEED.max(initial_velocity),
1790        };
1791
1792        SnappingSimulation {
1793            position,
1794            velocity,
1795            pixel_snap_size,
1796            tolerance,
1797        }
1798    }
1799
1800    // Find the two closest snap sizes to the position. If the velocity is
1801    // non-zero, select the size in the velocity's direction. Otherwise,
1802    // the nearest snap size.
1803    fn get_snap_size(
1804        position: f64,
1805        initial_velocity: f64,
1806        pixel_snap_sizes: &[f64],
1807        tolerance: Tolerance,
1808    ) -> f64 {
1809        let index_of_next_size = pixel_snap_sizes.iter().position(|size| *size >= position);
1810        if index_of_next_size == Some(0) {
1811            return pixel_snap_sizes[0];
1812        }
1813        let index_of_next_size =
1814            index_of_next_size.expect("the position is at or below the largest snap size");
1815        let next_size = pixel_snap_sizes[index_of_next_size];
1816        // If already snapped - keep this as target size
1817        if next_size == position {
1818            return next_size;
1819        }
1820        let previous_size = pixel_snap_sizes[index_of_next_size - 1];
1821        if initial_velocity.abs() <= tolerance.velocity {
1822            // If velocity is zero, snap to the nearest snap size with the minimum velocity.
1823            if position - previous_size < next_size - position {
1824                return previous_size;
1825            }
1826            return next_size;
1827        }
1828        // Snap forward or backward depending on current velocity.
1829        if initial_velocity < 0.0 {
1830            return pixel_snap_sizes[index_of_next_size - 1];
1831        }
1832        pixel_snap_sizes[index_of_next_size]
1833    }
1834}
1835
1836impl Simulation for SnappingSimulation {
1837    fn x(&self, time: f64) -> f64 {
1838        let new_position = self.position + self.velocity * time;
1839        if (self.velocity >= 0.0 && new_position > self.pixel_snap_size)
1840            || (self.velocity < 0.0 && new_position < self.pixel_snap_size)
1841        {
1842            // We're passed the snap size, return it instead.
1843            return self.pixel_snap_size;
1844        }
1845        new_position
1846    }
1847
1848    fn dx(&self, time: f64) -> f64 {
1849        if self.is_done(time) {
1850            return 0.0;
1851        }
1852        self.velocity
1853    }
1854
1855    fn is_done(&self, time: f64) -> bool {
1856        self.x(time) == self.pixel_snap_size
1857    }
1858
1859    fn tolerance(&self) -> Tolerance {
1860        self.tolerance
1861    }
1862
1863    fn set_tolerance(&mut self, tolerance: Tolerance) {
1864        self.tolerance = tolerance;
1865    }
1866}
1867
1868#[cfg(test)]
1869mod tests {
1870    use std::cell::Cell;
1871
1872    use waft_animation::Curves;
1873    use waft_embedder::{Offset, TextDirection};
1874    use waft_gestures::{DragEndDetails, DragUpdateDetails, Velocity};
1875
1876    use super::*;
1877    use crate::testing::{WidgetTester, test_widgets};
1878    use crate::widgets::basic::{Builder, Directionality};
1879    use crate::widgets::media_query::{MediaQuery, MediaQueryData};
1880    use crate::widgets::single_child_scroll_view::SingleChildScrollView;
1881
1882    const VIEW_HEIGHT: f64 = WidgetTester::SIZE.height();
1883
1884    /// The tree every test mounts: a text direction and a media query, which a `Scrollable`
1885    /// reads for its gesture settings.
1886    fn wrap<K>(child: impl IntoWidget<K>) -> WidgetRef {
1887        let query: WidgetRef =
1888            MediaQuery::new(MediaQueryData::new().size(WidgetTester::SIZE), child).into_widget();
1889        Directionality::new(TextDirection::Ltr, query).into_widget()
1890    }
1891
1892    /// A builder that puts a scroll view taller than the view under the sheet's controller.
1893    fn scrollable_builder() -> ScrollableWidgetBuilder {
1894        Rc::new(|_app, _context, controller| {
1895            SingleChildScrollView::new()
1896                .controller(controller)
1897                .child(
1898                    SizedBox::new()
1899                        .height(2.5 * VIEW_HEIGHT)
1900                        .width(WidgetTester::SIZE.width()),
1901                )
1902                .into_widget()
1903        })
1904    }
1905
1906    fn drag_by(delta: f64) -> DragUpdateDetails {
1907        DragUpdateDetails::new(
1908            Offset::ZERO,
1909            None,
1910            Some(Duration::ZERO),
1911            Offset::new(0.0, delta),
1912            Some(delta),
1913            None,
1914        )
1915    }
1916
1917    fn position(
1918        app: &App,
1919        controller: Ref<DraggableScrollableController>,
1920    ) -> Handle<DraggableScrollableSheetScrollPosition> {
1921        controller.attached_controller(app).position(app)
1922    }
1923
1924    #[test]
1925    fn the_sheet_starts_at_the_initial_child_size() {
1926        test_widgets(|tester| {
1927            let controller = tester.update(DraggableScrollableController::new);
1928            tester.pump_widget(wrap(
1929                DraggableScrollableSheet::new(scrollable_builder())
1930                    .initial_child_size(0.4)
1931                    .controller(controller.clone()),
1932            ));
1933            let app = tester.cell.borrow();
1934
1935            assert!(controller.is_attached(&app));
1936            assert_eq!(controller.size(&app), 0.4);
1937            // The whole view height is available, so the sheet is 40% of it.
1938            assert_eq!(controller.pixels(&app), VIEW_HEIGHT * 0.4);
1939        });
1940    }
1941
1942    #[test]
1943    fn a_drag_on_the_scrollable_grows_the_sheet_up_to_the_max_child_size() {
1944        test_widgets(|tester| {
1945            let controller = tester.update(DraggableScrollableController::new);
1946            tester.pump_widget(wrap(
1947                DraggableScrollableSheet::new(scrollable_builder())
1948                    .initial_child_size(0.5)
1949                    .controller(controller.clone()),
1950            ));
1951            let mut app = tester.cell.borrow_mut();
1952
1953            let position = position(&app, controller.clone());
1954            let drag = ScrollPosition::drag(
1955                position,
1956                &mut app,
1957                waft_gestures::DragStartDetails::default(),
1958                Listener::new(|_app| {}),
1959            );
1960
1961            // Dragging up by a fifth of the view grows the sheet by a fifth.
1962            drag.update(&mut app, drag_by(-VIEW_HEIGHT / 5.0));
1963            assert!(
1964                (controller.size(&app) - 0.7).abs() < 1e-9,
1965                "{}",
1966                controller.size(&app)
1967            );
1968            // The sheet, not the list, took the drag.
1969            assert_eq!(waft_rendering::ViewportOffset::pixels(position, &app), 0.0);
1970
1971            // Past the maximum it stops at the maximum, and then the list scrolls.
1972            drag.update(&mut app, drag_by(-VIEW_HEIGHT));
1973            assert_eq!(controller.size(&app), 1.0);
1974            drag.update(&mut app, drag_by(-10.0));
1975            assert_eq!(controller.size(&app), 1.0);
1976            assert!(waft_rendering::ViewportOffset::pixels(position, &app) > 0.0);
1977
1978            drag.end(
1979                &mut app,
1980                DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
1981            );
1982        });
1983    }
1984
1985    #[test]
1986    fn animate_to_reaches_the_size_and_notifies() {
1987        test_widgets(|tester| {
1988            let controller = tester.update(DraggableScrollableController::new);
1989            tester.pump_widget(wrap(
1990                DraggableScrollableSheet::new(scrollable_builder())
1991                    .initial_child_size(0.5)
1992                    .controller(controller.clone()),
1993            ));
1994
1995            let notified = Rc::new(Cell::new(0));
1996            let counter = Rc::clone(&notified);
1997            tester.update(|app| {
1998                ListenableObject::add_listener(
1999                    controller.handle(),
2000                    app,
2001                    Listener::new(move |_app| counter.set(counter.get() + 1)),
2002                )
2003            });
2004
2005            let done = tester.update(|app| {
2006                controller.animate_to(app, 0.8, Duration::from_millis(100), Curves::linear())
2007            });
2008
2009            tester.pump();
2010            tester.pump_by(Duration::from_millis(50));
2011            let size = controller.size(&tester.cell.borrow());
2012            assert!((size - 0.65).abs() < 0.01, "{size}");
2013            assert!(!done.is_completed());
2014
2015            tester.pump_by(Duration::from_millis(50));
2016            let size = controller.size(&tester.cell.borrow());
2017            assert!((size - 0.8).abs() < 1e-9, "{size}");
2018            assert!(notified.get() > 0);
2019            // The frame past the duration ends the animation, and the pump's checkpoint runs
2020            // the continuation after it.
2021            tester.pump_by(Duration::from_millis(50));
2022            assert!(done.is_completed());
2023        });
2024    }
2025
2026    #[test]
2027    fn a_snapping_sheet_settles_on_the_nearest_snap_size() {
2028        test_widgets(|tester| {
2029            let controller = tester.update(DraggableScrollableController::new);
2030            tester.pump_widget(wrap(
2031                DraggableScrollableSheet::new(scrollable_builder())
2032                    .initial_child_size(0.5)
2033                    .snap(true)
2034                    .snap_sizes(vec![0.5])
2035                    .controller(controller.clone()),
2036            ));
2037
2038            tester.update(|app| {
2039                let position = position(app, controller.clone());
2040                let drag = ScrollPosition::drag(
2041                    position,
2042                    app,
2043                    waft_gestures::DragStartDetails::default(),
2044                    Listener::new(|_app| {}),
2045                );
2046                // A drag up past the fling threshold, released with no velocity.
2047                drag.update(app, drag_by(-VIEW_HEIGHT * 0.15));
2048                assert!(
2049                    (controller.size(app) - 0.65).abs() < 1e-9,
2050                    "{}",
2051                    controller.size(app)
2052                );
2053                drag.end(
2054                    app,
2055                    DragEndDetails::new(Offset::ZERO, None, Velocity::ZERO, Some(0.0)),
2056                );
2057            });
2058
2059            tester.pump();
2060            for _ in 0..200 {
2061                if (controller.size(&tester.cell.borrow()) - 0.5).abs() < 1e-9 {
2062                    break;
2063                }
2064                tester.pump_by(Duration::from_millis(16));
2065            }
2066            // The snap sizes are the min, the given 0.5 and the max; 0.65 is nearest 0.5.
2067            assert_eq!(controller.size(&tester.cell.borrow()), 0.5);
2068        });
2069    }
2070
2071    #[test]
2072    fn the_actuator_resets_the_sheet_to_its_initial_size() {
2073        test_widgets(|tester| {
2074            let controller = tester.update(DraggableScrollableController::new);
2075            let inner_context: Rc<Cell<Option<BuildContext>>> = Rc::new(Cell::new(None));
2076            let reported = Rc::clone(&inner_context);
2077            let sheet_controller = controller.clone();
2078            tester.pump_widget(wrap(DraggableScrollableActuator::new(Builder::new(
2079                move |_app, context| {
2080                    reported.set(Some(context));
2081                    DraggableScrollableSheet::new(scrollable_builder())
2082                        .initial_child_size(0.5)
2083                        .controller(sheet_controller.clone())
2084                        .into_widget()
2085                },
2086            ))));
2087
2088            tester.update(|app| controller.jump_to(app, 0.9));
2089            assert_eq!(controller.size(&tester.cell.borrow()), 0.9);
2090
2091            let context = inner_context.get().expect("the builder ran");
2092            assert!(tester.update(|app| DraggableScrollableActuator::reset(app, context)));
2093            tester.pump_by(Duration::from_millis(16));
2094
2095            assert_eq!(controller.size(&tester.cell.borrow()), 0.5);
2096        });
2097    }
2098}