Skip to main content

waft_widgets/widgets/
dismissible.rs

1//! Flutter counterpart: `widgets/dismissible.dart`.
2//!
3//! A [`Dismissible`] slides its child away along the drag, asks
4//! [`confirm_dismiss`](Dismissible::confirm_dismiss) whether to go, then collapses its
5//! background to nothing before it calls [`on_dismissed`](Dismissible::on_dismissed). The
6//! state keeps itself alive while either animation runs.
7
8use std::any::Any;
9use std::collections::HashMap;
10use std::fmt::{self, Debug};
11use std::rc::Rc;
12use std::time::Duration;
13
14use waft_animation::{
15    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatus,
16    AnimationStatusListener, CurveTween, Curves, Drive, Interval, Tween,
17};
18use waft_embedder::{Offset, Rect, Size, TextDirection};
19use waft_foundation::{
20    App, AsyncApp, Handle, Listenable, Listener, OptionRetained, Task, VoidCallback,
21};
22use waft_gestures::{
23    DragEndDetails, DragStartBehavior, DragStartDetails, DragUpdateDetails, Velocity,
24};
25use waft_painting::Axis;
26use waft_rendering::{CustomClipper, HitTestBehavior};
27use waft_scheduler::{Ticker, TickerCallback, TickerProviderObject};
28
29use crate::framework::{
30    BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, WidgetRef,
31};
32use crate::widgets::automatic_keep_alive::{
33    AutomaticKeepAliveClientMixin, AutomaticKeepAliveClientMixinData,
34};
35use crate::widgets::basic::{ClipRect, Directionality, KeyedSubtree, Positioned, SizedBox, Stack};
36use crate::widgets::gesture_detector::GestureDetector;
37use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
38use crate::widgets::transitions::{SizeTransition, SlideTransition};
39use waft_foundation::Ref;
40
41/// Dart's `_kResizeTimeCurve`.
42fn k_resize_time_curve() -> Interval {
43    Interval::new(0.4, 1.0, Curves::ease())
44}
45const K_MIN_FLING_VELOCITY: f64 = 700.0;
46const K_MIN_FLING_VELOCITY_DELTA: f64 = 400.0;
47const K_FLING_VELOCITY_SCALE: f64 = 1.0 / 300.0;
48const K_DISMISS_THRESHOLD: f64 = 0.4;
49
50/// Signature used by [`Dismissible`] to indicate that it has been dismissed in the given
51/// `direction`.
52///
53/// Used by [`Dismissible::on_dismissed`].
54pub type DismissDirectionCallback = Rc<dyn Fn(&mut App, DismissDirection)>;
55
56/// Signature used by [`Dismissible`] to give the application an opportunity to confirm or veto
57/// a dismiss gesture.
58///
59/// Used by [`Dismissible::confirm_dismiss`].
60pub type ConfirmDismissCallback = Rc<dyn Fn(&mut App, DismissDirection) -> Task<Option<bool>>>;
61
62/// Signature used by [`Dismissible`] to indicate that the dismissible has been dragged.
63///
64/// Used by [`Dismissible::on_update`].
65pub type DismissUpdateCallback = Rc<dyn Fn(&mut App, DismissUpdateDetails)>;
66
67/// The direction in which a [`Dismissible`] can be dismissed.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub enum DismissDirection {
70    /// The [`Dismissible`] can be dismissed by dragging either up or down.
71    Vertical,
72
73    /// The [`Dismissible`] can be dismissed by dragging either left or right.
74    Horizontal,
75
76    /// The [`Dismissible`] can be dismissed by dragging in the reverse of the reading direction
77    /// (e.g., from right to left in left-to-right languages).
78    EndToStart,
79
80    /// The [`Dismissible`] can be dismissed by dragging in the reading direction (e.g., from
81    /// left to right in left-to-right languages).
82    StartToEnd,
83
84    /// The [`Dismissible`] can be dismissed by dragging up only.
85    Up,
86
87    /// The [`Dismissible`] can be dismissed by dragging down only.
88    Down,
89
90    /// The [`Dismissible`] cannot be dismissed by dragging.
91    None,
92}
93
94/// A widget that can be dismissed by dragging in the indicated [`direction`](Self::direction).
95///
96/// Dragging or flinging this widget in the [`DismissDirection`] causes the child to slide out
97/// of view. Following the slide animation, if [`resize_duration`](Self::resize_duration) is
98/// non-`None`, the Dismissible widget animates its height (or width, whichever is perpendicular
99/// to the dismiss direction) to zero over the [`resize_duration`](Self::resize_duration).
100///
101/// Backgrounds can be used to implement the "leave-behind" idiom. If a background is specified
102/// it is stacked behind the Dismissible's child and is exposed when the child moves.
103///
104/// The widget calls the [`on_dismissed`](Self::on_dismissed) callback either after its size has
105/// collapsed to zero (if [`resize_duration`](Self::resize_duration) is non-`None`) or
106/// immediately after the slide animation (if [`resize_duration`](Self::resize_duration) is
107/// `None`). If the Dismissible is a list item, it must have a key that distinguishes it from
108/// the other items and its [`on_dismissed`](Self::on_dismissed) callback must remove the item
109/// from the list.
110pub struct Dismissible {
111    /// See [`StatefulWidget::key`].
112    pub key: KeyRef,
113
114    /// The widget below this widget in the tree.
115    pub child: WidgetRef,
116
117    /// A widget that is stacked behind the child. If secondary_background is also specified
118    /// then this widget only appears when the child has been dragged down or to the right.
119    pub background: Option<WidgetRef>,
120
121    /// A widget that is stacked behind the child and is exposed when the child has been dragged
122    /// up or to the left. It may only be specified when background has also been specified.
123    pub secondary_background: Option<WidgetRef>,
124
125    /// Gives the app an opportunity to confirm or veto a pending dismissal.
126    ///
127    /// The widget cannot be dragged again until the returned future resolves.
128    ///
129    /// If the returned task completes `Some(true)`, then this widget will be dismissed,
130    /// otherwise it will be moved back to its original location.
131    ///
132    /// If the returned task completes to `Some(false)` or `None` the
133    /// [`on_resize`](Self::on_resize) and [`on_dismissed`](Self::on_dismissed) callbacks will
134    /// not run.
135    pub confirm_dismiss: Option<ConfirmDismissCallback>,
136
137    /// Called when the widget changes size (i.e., when contracting before being dismissed).
138    pub on_resize: Option<VoidCallback>,
139
140    /// Called when the widget has been dismissed, after finishing resizing.
141    pub on_dismissed: Option<DismissDirectionCallback>,
142
143    /// The direction in which the widget can be dismissed.
144    pub direction: DismissDirection,
145
146    /// The amount of time the widget will spend contracting before
147    /// [`on_dismissed`](Self::on_dismissed) is called.
148    ///
149    /// If `None`, the widget will not contract and [`on_dismissed`](Self::on_dismissed) will be
150    /// called immediately after the widget is dismissed.
151    pub resize_duration: Option<Duration>,
152
153    /// The offset threshold the item has to be dragged in order to be considered dismissed.
154    ///
155    /// Represented as a fraction, e.g. if it is 0.4 (the default), then the item has to be
156    /// dragged at least 40% towards one direction to be considered dismissed. Clients can
157    /// define different thresholds for each dismiss direction.
158    ///
159    /// Flinging is treated as being equivalent to dragging almost to 1.0, so flinging can
160    /// dismiss an item past any threshold less than 1.0.
161    ///
162    /// Setting a threshold of 1.0 (or greater) prevents a drag in the given [`DismissDirection`]
163    /// even if it would be allowed by the [`direction`](Self::direction) property.
164    ///
165    /// See also:
166    ///
167    ///  * [`direction`](Self::direction), which controls the directions in which the items can
168    ///    be dismissed.
169    pub dismiss_thresholds: HashMap<DismissDirection, f64>,
170
171    /// Defines the duration for card to dismiss or to come back to original position if not
172    /// dismissed.
173    pub movement_duration: Duration,
174
175    /// Defines the end offset across the main axis after the card is dismissed.
176    ///
177    /// If non-zero value is given then widget moves in cross direction depending on whether it
178    /// is positive or negative.
179    pub cross_axis_end_offset: f64,
180
181    /// Determines the way that drag start behavior is handled.
182    ///
183    /// If set to [`DragStartBehavior::Start`], the drag gesture used to dismiss a dismissible
184    /// will begin at the position where the drag gesture won the arena. If set to
185    /// [`DragStartBehavior::Down`] it will begin at the position where a down event is first
186    /// detected.
187    ///
188    /// In general, setting this to [`DragStartBehavior::Start`] will make drag animation
189    /// smoother and setting it to [`DragStartBehavior::Down`] will make drag behavior feel
190    /// slightly more reactive.
191    ///
192    /// By default, the drag start behavior is [`DragStartBehavior::Start`].
193    pub drag_start_behavior: DragStartBehavior,
194
195    /// How to behave during hit tests.
196    ///
197    /// This defaults to [`HitTestBehavior::Opaque`].
198    pub behavior: HitTestBehavior,
199
200    /// Called when the dismissible widget has been dragged.
201    ///
202    /// If [`on_update`](Self::on_update) is not `None`, then it will be invoked for every
203    /// pointer event to dispatch the latest state of the drag. For example, this callback can be
204    /// used to for example change the color of the background widget depending on whether the
205    /// dismiss threshold is currently reached.
206    pub on_update: Option<DismissUpdateCallback>,
207}
208
209impl Dismissible {
210    /// Creates a widget that can be dismissed.
211    ///
212    /// The `key` argument is required because [`Dismissible`]s are commonly used in lists and
213    /// removed from the list when dismissed. Without keys, the default behavior is to sync
214    /// widgets based on their index in the list, which means the item after the dismissed item
215    /// would be synced with the state of the dismissed item. Using keys causes the widgets to
216    /// sync according to their keys and avoids this pitfall.
217    #[cfg_attr(debug_assertions, track_caller)]
218    pub fn new<K>(key: KeyRef, child: impl IntoWidget<K>) -> Dismissible {
219        Dismissible {
220            key,
221            child: child.into_widget(),
222            background: None,
223            secondary_background: None,
224            confirm_dismiss: None,
225            on_resize: None,
226            on_dismissed: None,
227            direction: DismissDirection::Horizontal,
228            resize_duration: Some(Duration::from_millis(300)),
229            dismiss_thresholds: HashMap::new(),
230            movement_duration: Duration::from_millis(200),
231            cross_axis_end_offset: 0.0,
232            drag_start_behavior: DragStartBehavior::Start,
233            behavior: HitTestBehavior::Opaque,
234            on_update: None,
235        }
236    }
237
238    /// Dart `Dismissible(background:)`.
239    #[cfg_attr(debug_assertions, track_caller)]
240    pub fn background<K>(mut self, background: impl IntoWidget<K>) -> Dismissible {
241        self.background = Some(background.into_widget());
242        self
243    }
244
245    /// Dart `Dismissible(secondaryBackground:)`.
246    #[cfg_attr(debug_assertions, track_caller)]
247    pub fn secondary_background<K>(
248        mut self,
249        secondary_background: impl IntoWidget<K>,
250    ) -> Dismissible {
251        self.secondary_background = Some(secondary_background.into_widget());
252        self
253    }
254
255    /// Dart `Dismissible(confirmDismiss:)`.
256    pub fn confirm_dismiss(
257        mut self,
258        confirm_dismiss: impl Fn(&mut App, DismissDirection) -> Task<Option<bool>> + 'static,
259    ) -> Dismissible {
260        self.confirm_dismiss = Some(Rc::new(confirm_dismiss));
261        self
262    }
263
264    /// Dart `Dismissible(onResize:)`.
265    pub fn on_resize(mut self, on_resize: impl Fn(&mut App) + 'static) -> Dismissible {
266        self.on_resize = Some(Rc::new(on_resize));
267        self
268    }
269
270    /// Dart `Dismissible(onUpdate:)`.
271    pub fn on_update(
272        mut self,
273        on_update: impl Fn(&mut App, DismissUpdateDetails) + 'static,
274    ) -> Dismissible {
275        self.on_update = Some(Rc::new(on_update));
276        self
277    }
278
279    /// Dart `Dismissible(onDismissed:)`.
280    pub fn on_dismissed(
281        mut self,
282        on_dismissed: impl Fn(&mut App, DismissDirection) + 'static,
283    ) -> Dismissible {
284        self.on_dismissed = Some(Rc::new(on_dismissed));
285        self
286    }
287
288    /// Dart `Dismissible(direction:)`.
289    pub fn direction(mut self, direction: DismissDirection) -> Dismissible {
290        self.direction = direction;
291        self
292    }
293
294    /// Dart `Dismissible(resizeDuration:)`.
295    pub fn resize_duration(mut self, resize_duration: Option<Duration>) -> Dismissible {
296        self.resize_duration = resize_duration;
297        self
298    }
299
300    /// Dart `Dismissible(dismissThresholds:)`.
301    pub fn dismiss_thresholds(
302        mut self,
303        dismiss_thresholds: HashMap<DismissDirection, f64>,
304    ) -> Dismissible {
305        self.dismiss_thresholds = dismiss_thresholds;
306        self
307    }
308
309    /// Dart `Dismissible(movementDuration:)`.
310    pub fn movement_duration(mut self, movement_duration: Duration) -> Dismissible {
311        self.movement_duration = movement_duration;
312        self
313    }
314
315    /// Dart `Dismissible(crossAxisEndOffset:)`.
316    pub fn cross_axis_end_offset(mut self, cross_axis_end_offset: f64) -> Dismissible {
317        self.cross_axis_end_offset = cross_axis_end_offset;
318        self
319    }
320
321    /// Dart `Dismissible(dragStartBehavior:)`.
322    pub fn drag_start_behavior(mut self, drag_start_behavior: DragStartBehavior) -> Dismissible {
323        self.drag_start_behavior = drag_start_behavior;
324        self
325    }
326
327    /// Dart `Dismissible(behavior:)`.
328    pub fn behavior(mut self, behavior: HitTestBehavior) -> Dismissible {
329        self.behavior = behavior;
330        self
331    }
332}
333
334impl Debug for Dismissible {
335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336        f.debug_struct("Dismissible")
337            .field("key", &self.key)
338            .field("direction", &self.direction)
339            .field("resize_duration", &self.resize_duration)
340            .field("movement_duration", &self.movement_duration)
341            .field("cross_axis_end_offset", &self.cross_axis_end_offset)
342            .finish_non_exhaustive()
343    }
344}
345
346impl StatefulWidget for Dismissible {
347    type State = DismissibleState;
348
349    fn key(&self) -> Option<&KeyRef> {
350        Some(&self.key)
351    }
352
353    fn debug_check_constructor(&self) {
354        debug_assert!(self.secondary_background.is_none() || self.background.is_some());
355    }
356
357    fn create_state(&self) -> DismissibleState {
358        DismissibleState {
359            state: StateData::new(),
360            ticker_provider: TickerProviderStateMixinData::new(),
361            automatic_keep_alive_client: AutomaticKeepAliveClientMixinData::new(),
362            move_controller: None,
363            move_animation: None,
364            resize_controller: None,
365            resize_animation: None,
366            drag_extent: 0.0,
367            confirming: false,
368            drag_underway: false,
369            size_prior_to_collapse: None,
370            dismiss_threshold_reached: false,
371            content_key: GlobalKey::new(),
372        }
373    }
374}
375
376/// Details for [`DismissUpdateCallback`].
377///
378/// See also:
379///
380///   * [`Dismissible::on_update`], which receives this information.
381#[derive(Clone, Copy, Debug)]
382pub struct DismissUpdateDetails {
383    /// The direction that the dismissible is being dragged.
384    pub direction: DismissDirection,
385
386    /// Whether the dismiss threshold is currently reached.
387    pub reached: bool,
388
389    /// Whether the dismiss threshold was reached the last time this callback was invoked.
390    ///
391    /// This can be used in conjunction with [`reached`](Self::reached) to catch the moment that
392    /// the [`Dismissible`] is dragged across the threshold.
393    pub previous_reached: bool,
394
395    /// The offset ratio of the dismissible in its parent container.
396    ///
397    /// A value of 0.0 represents the normal position and 1.0 means the child is completely
398    /// outside its parent.
399    ///
400    /// This can be used to synchronize other elements to what the dismissible is doing on
401    /// screen, e.g. using this value to set the opacity thereby fading dismissible as it's
402    /// dragged offscreen.
403    pub progress: f64,
404}
405
406impl DismissUpdateDetails {
407    /// Create a new instance of [`DismissUpdateDetails`].
408    pub fn new() -> DismissUpdateDetails {
409        DismissUpdateDetails {
410            direction: DismissDirection::Horizontal,
411            reached: false,
412            previous_reached: false,
413            progress: 0.0,
414        }
415    }
416
417    /// Dart `DismissUpdateDetails(direction:)`.
418    pub fn direction(mut self, direction: DismissDirection) -> DismissUpdateDetails {
419        self.direction = direction;
420        self
421    }
422
423    /// Dart `DismissUpdateDetails(reached:)`.
424    pub fn reached(mut self, reached: bool) -> DismissUpdateDetails {
425        self.reached = reached;
426        self
427    }
428
429    /// Dart `DismissUpdateDetails(previousReached:)`.
430    pub fn previous_reached(mut self, previous_reached: bool) -> DismissUpdateDetails {
431        self.previous_reached = previous_reached;
432        self
433    }
434
435    /// Dart `DismissUpdateDetails(progress:)`.
436    pub fn progress(mut self, progress: f64) -> DismissUpdateDetails {
437        self.progress = progress;
438        self
439    }
440}
441
442impl Default for DismissUpdateDetails {
443    fn default() -> DismissUpdateDetails {
444        DismissUpdateDetails::new()
445    }
446}
447
448/// Dart's `_DismissibleClipper`.
449struct DismissibleClipper {
450    axis: Axis,
451    move_animation: AnimationRef<Offset>,
452    reclip: Rc<dyn Listenable>,
453}
454
455impl DismissibleClipper {
456    fn new(axis: Axis, move_animation: AnimationRef<Offset>) -> DismissibleClipper {
457        DismissibleClipper {
458            axis,
459            reclip: Rc::new(move_animation.clone()),
460            move_animation,
461        }
462    }
463}
464
465impl CustomClipper<Rect> for DismissibleClipper {
466    fn reclip(&self) -> Option<&Rc<dyn Listenable>> {
467        Some(&self.reclip)
468    }
469
470    fn get_clip(&self, app: &App, size: Size) -> Rect {
471        match self.axis {
472            Axis::Horizontal => {
473                let offset = self.move_animation.value(app).dx() * size.width();
474                if offset < 0.0 {
475                    return Rect::from_ltrb(
476                        size.width() + offset,
477                        0.0,
478                        size.width(),
479                        size.height(),
480                    );
481                }
482                Rect::from_ltrb(0.0, 0.0, offset, size.height())
483            }
484            Axis::Vertical => {
485                let offset = self.move_animation.value(app).dy() * size.height();
486                if offset < 0.0 {
487                    return Rect::from_ltrb(
488                        0.0,
489                        size.height() + offset,
490                        size.width(),
491                        size.height(),
492                    );
493                }
494                Rect::from_ltrb(0.0, 0.0, size.width(), offset)
495            }
496        }
497    }
498
499    fn get_approximate_clip_rect(&self, app: &App, size: Size) -> Rect {
500        self.get_clip(app, size)
501    }
502
503    fn should_reclip(&self, app: &App, old_clipper: &dyn CustomClipper<Rect>) -> bool {
504        let old_clipper = old_clipper
505            .as_any()
506            .downcast_ref::<DismissibleClipper>()
507            .expect("compared with a clipper of its own type");
508        old_clipper.axis != self.axis
509            || old_clipper.move_animation.value(app) != self.move_animation.value(app)
510    }
511
512    fn as_any(&self) -> &dyn Any {
513        self
514    }
515}
516
517/// Dart's `_FlingGestureKind`.
518#[derive(Clone, Copy, Debug, PartialEq, Eq)]
519enum FlingGestureKind {
520    None,
521    Forward,
522    Reverse,
523}
524
525/// Dart's `double.sign`: -1.0, 0.0 or 1.0, where Rust's `signum` answers 1.0 for zero.
526fn sign(value: f64) -> f64 {
527    if value > 0.0 {
528        1.0
529    } else if value < 0.0 {
530        -1.0
531    } else {
532        value
533    }
534}
535
536/// Dart's `_DismissibleState`.
537pub struct DismissibleState {
538    state: StateData<Dismissible>,
539    ticker_provider: TickerProviderStateMixinData,
540    automatic_keep_alive_client: AutomaticKeepAliveClientMixinData,
541    // Dart's `late final`: created in `init_state`, which has the `App`.
542    move_controller: Option<Ref<AnimationController>>,
543    move_animation: Option<AnimationRef<Offset>>,
544    resize_controller: Option<Ref<AnimationController>>,
545    resize_animation: Option<AnimationRef<f64>>,
546    drag_extent: f64,
547    confirming: bool,
548    drag_underway: bool,
549    size_prior_to_collapse: Option<Size>,
550    dismiss_threshold_reached: bool,
551    content_key: GlobalKey,
552}
553
554impl DismissibleState {
555    fn move_controller(self: Handle<Self>, app: &App) -> Handle<AnimationController> {
556        app.get(self)
557            .move_controller
558            .handle()
559            .expect("created in init_state")
560    }
561
562    fn direction_is_x_axis(self: Handle<Self>, app: &App) -> bool {
563        let direction = self.widget(app).direction;
564        direction == DismissDirection::Horizontal
565            || direction == DismissDirection::EndToStart
566            || direction == DismissDirection::StartToEnd
567    }
568
569    fn extent_to_direction(self: Handle<Self>, app: &mut App, extent: f64) -> DismissDirection {
570        if extent == 0.0 {
571            return DismissDirection::None;
572        }
573        if self.direction_is_x_axis(app) {
574            let context = self.context(app);
575            return match Directionality::of(app, context) {
576                TextDirection::Rtl if extent < 0.0 => DismissDirection::StartToEnd,
577                TextDirection::Ltr if extent > 0.0 => DismissDirection::StartToEnd,
578                TextDirection::Rtl | TextDirection::Ltr => DismissDirection::EndToStart,
579            };
580        }
581        if extent > 0.0 {
582            DismissDirection::Down
583        } else {
584            DismissDirection::Up
585        }
586    }
587
588    fn dismiss_direction(self: Handle<Self>, app: &mut App) -> DismissDirection {
589        let drag_extent = app.get(self).drag_extent;
590        self.extent_to_direction(app, drag_extent)
591    }
592
593    fn dismiss_threshold(self: Handle<Self>, app: &mut App) -> f64 {
594        let direction = self.dismiss_direction(app);
595        self.widget(app)
596            .dismiss_thresholds
597            .get(&direction)
598            .copied()
599            .unwrap_or(K_DISMISS_THRESHOLD)
600    }
601
602    fn overall_drag_axis_extent(self: Handle<Self>, app: &App) -> f64 {
603        let size = self
604            .context(app)
605            .size(app)
606            .expect("a dragged dismissible has been laid out");
607        if self.direction_is_x_axis(app) {
608            size.width()
609        } else {
610            size.height()
611        }
612    }
613
614    fn handle_drag_start(self: Handle<Self>, app: &mut App, _details: DragStartDetails) {
615        if app.get(self).confirming {
616            return;
617        }
618        app.get_mut(self).drag_underway = true;
619        let move_controller = self.move_controller(app);
620        if move_controller.is_animating(app) {
621            let value = move_controller.value(app);
622            let overall_drag_axis_extent = self.overall_drag_axis_extent(app);
623            let drag_extent = app.get(self).drag_extent;
624            app.get_mut(self).drag_extent = value * overall_drag_axis_extent * sign(drag_extent);
625            move_controller.stop(app, true);
626        } else {
627            app.get_mut(self).drag_extent = 0.0;
628            move_controller.set_value(app, 0.0);
629        }
630        self.update_move_animation(app);
631        self.set_state(app, |_state| {});
632    }
633
634    fn handle_drag_update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
635        let move_controller = self.move_controller(app);
636        if !app.get(self).drag_underway || move_controller.is_animating(app) {
637            return;
638        }
639
640        let delta = details
641            .primary_delta
642            .expect("a drag along one axis has a primary delta");
643        let old_drag_extent = app.get(self).drag_extent;
644        let drag_extent = old_drag_extent;
645        let new_drag_extent = match self.widget(app).direction {
646            DismissDirection::Horizontal | DismissDirection::Vertical => drag_extent + delta,
647
648            DismissDirection::Up => {
649                if drag_extent + delta < 0.0 {
650                    drag_extent + delta
651                } else {
652                    drag_extent
653                }
654            }
655
656            DismissDirection::Down => {
657                if drag_extent + delta > 0.0 {
658                    drag_extent + delta
659                } else {
660                    drag_extent
661                }
662            }
663
664            DismissDirection::EndToStart => {
665                let context = self.context(app);
666                match Directionality::of(app, context) {
667                    TextDirection::Rtl => {
668                        if drag_extent + delta > 0.0 {
669                            drag_extent + delta
670                        } else {
671                            drag_extent
672                        }
673                    }
674                    TextDirection::Ltr => {
675                        if drag_extent + delta < 0.0 {
676                            drag_extent + delta
677                        } else {
678                            drag_extent
679                        }
680                    }
681                }
682            }
683
684            DismissDirection::StartToEnd => {
685                let context = self.context(app);
686                match Directionality::of(app, context) {
687                    TextDirection::Rtl => {
688                        if drag_extent + delta < 0.0 {
689                            drag_extent + delta
690                        } else {
691                            drag_extent
692                        }
693                    }
694                    TextDirection::Ltr => {
695                        if drag_extent + delta > 0.0 {
696                            drag_extent + delta
697                        } else {
698                            drag_extent
699                        }
700                    }
701                }
702            }
703
704            DismissDirection::None => 0.0,
705        };
706        app.get_mut(self).drag_extent = new_drag_extent;
707        if sign(old_drag_extent) != sign(new_drag_extent) {
708            self.update_move_animation(app);
709            self.set_state(app, |_state| {});
710        }
711        if !move_controller.is_animating(app) {
712            let overall_drag_axis_extent = self.overall_drag_axis_extent(app);
713            move_controller.set_value(app, new_drag_extent.abs() / overall_drag_axis_extent);
714        }
715    }
716
717    fn handle_dismiss_update_value_changed(self: Handle<Self>, app: &mut App) {
718        if let Some(on_update) = self.widget(app).on_update.clone() {
719            let old_dismiss_threshold_reached = app.get(self).dismiss_threshold_reached;
720            let value = self.move_controller(app).value(app);
721            let dismiss_threshold = self.dismiss_threshold(app);
722            app.get_mut(self).dismiss_threshold_reached = value > dismiss_threshold;
723            let details = DismissUpdateDetails::new()
724                .direction(self.dismiss_direction(app))
725                .reached(app.get(self).dismiss_threshold_reached)
726                .previous_reached(old_dismiss_threshold_reached)
727                .progress(value);
728            on_update(app, details);
729        }
730    }
731
732    fn update_move_animation(self: Handle<Self>, app: &mut App) {
733        let end = sign(app.get(self).drag_extent);
734        let cross_axis_end_offset = self.widget(app).cross_axis_end_offset;
735        let end_offset = if self.direction_is_x_axis(app) {
736            Offset::new(end, cross_axis_end_offset)
737        } else {
738            Offset::new(cross_axis_end_offset, end)
739        };
740        let tween = Tween::new(app, Some(Offset::ZERO), Some(end_offset));
741        let move_controller = app
742            .get(self)
743            .move_controller
744            .clone()
745            .expect("created in init_state");
746        let move_animation = move_controller.drive(app, tween);
747        app.get_mut(self).move_animation = Some(move_animation);
748    }
749
750    fn describe_fling_gesture(
751        self: Handle<Self>,
752        app: &mut App,
753        velocity: Velocity,
754    ) -> FlingGestureKind {
755        if app.get(self).drag_extent == 0.0 {
756            // If it was a fling, then it was a fling that was let loose at the exact
757            // middle of the range (i.e. when there's no displacement). In that case,
758            // we assume that the user meant to fling it back to the center, as
759            // opposed to having wanted to drag it out one way, then fling it past the
760            // center and into and out the other side.
761            return FlingGestureKind::None;
762        }
763        let vx = velocity.pixels_per_second.dx();
764        let vy = velocity.pixels_per_second.dy();
765        // Verify that the fling is in the generally right direction and fast enough.
766        let fling_direction = if self.direction_is_x_axis(app) {
767            if vx.abs() - vy.abs() < K_MIN_FLING_VELOCITY_DELTA || vx.abs() < K_MIN_FLING_VELOCITY {
768                return FlingGestureKind::None;
769            }
770            debug_assert!(vx != 0.0);
771            self.extent_to_direction(app, vx)
772        } else {
773            if vy.abs() - vx.abs() < K_MIN_FLING_VELOCITY_DELTA || vy.abs() < K_MIN_FLING_VELOCITY {
774                return FlingGestureKind::None;
775            }
776            debug_assert!(vy != 0.0);
777            self.extent_to_direction(app, vy)
778        };
779        if fling_direction == self.dismiss_direction(app) {
780            return FlingGestureKind::Forward;
781        }
782        FlingGestureKind::Reverse
783    }
784
785    fn handle_drag_end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
786        let move_controller = self.move_controller(app);
787        if !app.get(self).drag_underway || move_controller.is_animating(app) {
788            return;
789        }
790        app.get_mut(self).drag_underway = false;
791        if move_controller.status(app).is_completed() {
792            drop(self.handle_move_completed(app));
793            return;
794        }
795        let fling_velocity = if self.direction_is_x_axis(app) {
796            details.velocity.pixels_per_second.dx()
797        } else {
798            details.velocity.pixels_per_second.dy()
799        };
800        match self.describe_fling_gesture(app, details.velocity) {
801            FlingGestureKind::Forward => {
802                debug_assert!(app.get(self).drag_extent != 0.0);
803                debug_assert!(!move_controller.status(app).is_dismissed());
804                if self.dismiss_threshold(app) >= 1.0 {
805                    move_controller.reverse(app, None);
806                    return;
807                }
808                app.get_mut(self).drag_extent = sign(fling_velocity);
809                move_controller.fling(
810                    app,
811                    fling_velocity.abs() * K_FLING_VELOCITY_SCALE,
812                    None,
813                    None,
814                );
815            }
816            FlingGestureKind::Reverse => {
817                debug_assert!(app.get(self).drag_extent != 0.0);
818                debug_assert!(!move_controller.status(app).is_dismissed());
819                app.get_mut(self).drag_extent = sign(fling_velocity);
820                move_controller.fling(
821                    app,
822                    -fling_velocity.abs() * K_FLING_VELOCITY_SCALE,
823                    None,
824                    None,
825                );
826            }
827            FlingGestureKind::None => {
828                if !move_controller.status(app).is_dismissed() {
829                    // we already know it's not completed, we check that above
830                    if move_controller.value(app) > self.dismiss_threshold(app) {
831                        move_controller.forward(app, None);
832                    } else {
833                        move_controller.reverse(app, None);
834                    }
835                }
836            }
837        }
838    }
839
840    fn handle_dismiss_status_changed(
841        self: Handle<Self>,
842        app: &mut App,
843        status: AnimationStatus,
844    ) -> Task<()> {
845        if status.is_completed() && !app.get(self).drag_underway {
846            let move_completed = self.handle_move_completed(app);
847            return app.spawn(async move |cx| {
848                move_completed.await;
849                cx.update(|app| {
850                    if self.mounted(app) {
851                        self.update_keep_alive(app);
852                    }
853                });
854            });
855        }
856        if self.mounted(app) {
857            self.update_keep_alive(app);
858        }
859        Task::ready(())
860    }
861
862    fn handle_move_completed(self: Handle<Self>, app: &mut App) -> Task<()> {
863        if self.dismiss_threshold(app) >= 1.0 {
864            self.move_controller(app).reverse(app, None);
865            return Task::ready(());
866        }
867        let confirmation = self.confirm_start_resize_animation(app);
868        app.spawn(async move |cx| {
869            let result = confirmation.await;
870            cx.update(|app| {
871                if self.mounted(app) {
872                    if result {
873                        self.start_resize_animation(app);
874                    } else {
875                        self.move_controller(app).reverse(app, None);
876                    }
877                }
878            });
879        })
880    }
881
882    fn confirm_start_resize_animation(self: Handle<Self>, app: &mut App) -> Task<bool> {
883        if let Some(confirm_dismiss) = self.widget(app).confirm_dismiss.clone() {
884            app.get_mut(self).confirming = true;
885            let direction = self.dismiss_direction(app);
886            let confirmation = confirm_dismiss(app, direction);
887            return app.spawn(async move |cx| {
888                let _confirming = ConfirmingGuard {
889                    state: self,
890                    cx: cx.clone(),
891                };
892                confirmation.await.unwrap_or(false)
893            });
894        }
895        Task::ready(true)
896    }
897
898    fn start_resize_animation(self: Handle<Self>, app: &mut App) {
899        debug_assert!(self.move_controller(app).status(app).is_completed());
900        debug_assert!(app.get(self).resize_controller.is_none());
901        debug_assert!(app.get(self).size_prior_to_collapse.is_none());
902        match self.widget(app).resize_duration {
903            None => {
904                if let Some(on_dismissed) = self.widget(app).on_dismissed.clone() {
905                    let direction = self.dismiss_direction(app);
906                    on_dismissed(app, direction);
907                }
908            }
909            Some(resize_duration) => {
910                let resize_controller = AnimationController::new(
911                    app,
912                    None,
913                    Some(resize_duration),
914                    None,
915                    0.0,
916                    1.0,
917                    AnimationBehavior::Normal,
918                    self,
919                );
920                resize_controller.add_listener(
921                    app,
922                    Listener::handle_method(self, Self::handle_resize_progress_changed),
923                );
924                resize_controller.add_status_listener(
925                    app,
926                    AnimationStatusListener::new(move |_status, app| self.update_keep_alive(app)),
927                );
928                app.get_mut(self).resize_controller = Some(resize_controller.clone());
929                resize_controller.forward(app, None);
930                let size_prior_to_collapse = self.context(app).size(app);
931                let curve_tween = CurveTween::new(app, Rc::new(k_resize_time_curve()));
932                let curved = resize_controller.drive(app, curve_tween);
933                let tween = Tween::new(app, Some(1.0), Some(0.0));
934                let resize_animation = curved.drive(app, tween);
935                app.get_mut(self).size_prior_to_collapse = size_prior_to_collapse;
936                app.get_mut(self).resize_animation = Some(resize_animation);
937                self.set_state(app, |_state| {});
938            }
939        }
940    }
941
942    fn handle_resize_progress_changed(self: Handle<Self>, app: &mut App) {
943        let resize_controller = app
944            .get(self)
945            .resize_controller
946            .handle()
947            .expect("listening to the resize controller");
948        if resize_controller.status(app).is_completed() {
949            if let Some(on_dismissed) = self.widget(app).on_dismissed.clone() {
950                let direction = self.dismiss_direction(app);
951                on_dismissed(app, direction);
952            }
953        } else if let Some(on_resize) = self.widget(app).on_resize.clone() {
954            on_resize(app);
955        }
956    }
957}
958
959/// Dart's `finally { _confirming = false; }` around the wait for
960/// [`Dismissible::confirm_dismiss`]: it runs however the wait ends.
961struct ConfirmingGuard {
962    state: Handle<DismissibleState>,
963    cx: AsyncApp,
964}
965
966impl Drop for ConfirmingGuard {
967    fn drop(&mut self) {
968        let state = self.state;
969        // A state disposed while it waited has no slot to write to.
970        self.cx.update(|app| {
971            if state.mounted(app) {
972                app.get_mut(state).confirming = false;
973            }
974        });
975    }
976}
977
978impl TickerProviderObject for DismissibleState {
979    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
980        TickerProviderStateMixin::create_ticker(self, app, on_tick)
981    }
982}
983
984impl TickerProviderStateMixin for DismissibleState {
985    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
986        &app.get(self).ticker_provider
987    }
988
989    fn ticker_provider_data_mut(
990        self: Handle<Self>,
991        app: &mut App,
992    ) -> &mut TickerProviderStateMixinData {
993        &mut app.get_mut(self).ticker_provider
994    }
995}
996
997impl AutomaticKeepAliveClientMixin for DismissibleState {
998    fn automatic_keep_alive_client_data(
999        self: Handle<Self>,
1000        app: &App,
1001    ) -> &AutomaticKeepAliveClientMixinData {
1002        &app.get(self).automatic_keep_alive_client
1003    }
1004
1005    fn automatic_keep_alive_client_data_mut(
1006        self: Handle<Self>,
1007        app: &mut App,
1008    ) -> &mut AutomaticKeepAliveClientMixinData {
1009        &mut app.get_mut(self).automatic_keep_alive_client
1010    }
1011
1012    fn want_keep_alive(self: Handle<Self>, app: &App) -> bool {
1013        let move_controller = self.move_controller(app);
1014        Animation::is_animating(move_controller, app)
1015            || app
1016                .get(self)
1017                .resize_controller
1018                .as_ref()
1019                .is_some_and(|resize_controller| {
1020                    Animation::is_animating(resize_controller.handle(), app)
1021                })
1022    }
1023}
1024
1025impl State for DismissibleState {
1026    type Widget = Dismissible;
1027    crate::state_accessors!();
1028
1029    fn init_state(self: Handle<Self>, app: &mut App) {
1030        let movement_duration = self.widget(app).movement_duration;
1031        let move_controller = AnimationController::new(
1032            app,
1033            None,
1034            Some(movement_duration),
1035            None,
1036            0.0,
1037            1.0,
1038            AnimationBehavior::Normal,
1039            self,
1040        );
1041        app.get_mut(self).move_controller = Some(move_controller.clone());
1042        AutomaticKeepAliveClientMixin::init_state(self, app);
1043        move_controller.add_status_listener(
1044            app,
1045            AnimationStatusListener::new(move |status, app| {
1046                drop(self.handle_dismiss_status_changed(app, status));
1047            }),
1048        );
1049        move_controller.add_listener(
1050            app,
1051            Listener::handle_method(self, Self::handle_dismiss_update_value_changed),
1052        );
1053        self.update_move_animation(app);
1054    }
1055
1056    fn activate(self: Handle<Self>, app: &mut App) {
1057        TickerProviderStateMixin::activate(self, app);
1058    }
1059
1060    fn deactivate(self: Handle<Self>, app: &mut App) {
1061        AutomaticKeepAliveClientMixin::deactivate(self, app);
1062    }
1063
1064    fn dispose(self: Handle<Self>, app: &mut App) {
1065        self.move_controller(app).dispose(app);
1066        if let Some(resize_controller) = app.get(self).resize_controller.handle() {
1067            resize_controller.dispose(app);
1068        }
1069        TickerProviderStateMixin::dispose(self, app);
1070    }
1071
1072    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1073        AutomaticKeepAliveClientMixin::build(self, app); // See AutomaticKeepAliveClientMixin.
1074
1075        let direction_is_x_axis = self.direction_is_x_axis(app);
1076        let mut background = self.widget(app).background.clone();
1077        if self.widget(app).secondary_background.is_some() {
1078            let direction = self.dismiss_direction(app);
1079            if direction == DismissDirection::EndToStart || direction == DismissDirection::Up {
1080                background = self.widget(app).secondary_background.clone();
1081            }
1082        }
1083
1084        if let Some(resize_animation) = app.get(self).resize_animation.clone() {
1085            // we've been dragged aside, and are now resizing.
1086            if cfg!(debug_assertions) && resize_animation.status(app) != AnimationStatus::Forward {
1087                assert!(resize_animation.is_completed(app));
1088                panic!(
1089                    "A dismissed Dismissible widget is still part of the tree.\n\
1090                     Make sure to implement the onDismissed handler and to immediately remove \
1091                     the Dismissible widget from the application once that handler has fired."
1092                );
1093            }
1094
1095            let size_prior_to_collapse = app
1096                .get(self)
1097                .size_prior_to_collapse
1098                .expect("recorded as the resize started");
1099            let mut sized = SizedBox::new()
1100                .width(size_prior_to_collapse.width())
1101                .height(size_prior_to_collapse.height());
1102            if let Some(background) = background {
1103                sized = sized.child(background);
1104            }
1105            return SizeTransition::new(resize_animation)
1106                .axis(if direction_is_x_axis {
1107                    Axis::Vertical
1108                } else {
1109                    Axis::Horizontal
1110                })
1111                .child(sized)
1112                .into_widget();
1113        }
1114
1115        let move_animation = app
1116            .get(self)
1117            .move_animation
1118            .clone()
1119            .expect("created in init_state");
1120        let content_key = app.get(self).content_key.clone();
1121        let child = self.widget(app).child.clone();
1122        let mut content = SlideTransition::new(move_animation.clone())
1123            .child(KeyedSubtree::new(child).key(content_key.into()))
1124            .into_widget();
1125
1126        if let Some(background) = background {
1127            let mut children = Vec::new();
1128            if !move_animation.is_dismissed(app) {
1129                children.push(
1130                    Positioned::fill(
1131                        ClipRect::new()
1132                            .clipper(DismissibleClipper::new(
1133                                if direction_is_x_axis {
1134                                    Axis::Horizontal
1135                                } else {
1136                                    Axis::Vertical
1137                                },
1138                                move_animation,
1139                            ))
1140                            .child(background),
1141                    )
1142                    .into_widget(),
1143                );
1144            }
1145            children.push(content);
1146            content = Stack::new().children(children).into_widget();
1147        }
1148
1149        // If the DismissDirection is none, we do not add drag gestures because the content
1150        // cannot be dragged.
1151        if self.widget(app).direction == DismissDirection::None {
1152            return content;
1153        }
1154
1155        // We are not resizing but we may be being dragging in widget.direction.
1156        let on_drag_start = Rc::new(move |app: &mut App, details: DragStartDetails| {
1157            self.handle_drag_start(app, details);
1158        });
1159        let on_drag_update = Rc::new(move |app: &mut App, details: DragUpdateDetails| {
1160            self.handle_drag_update(app, details);
1161        });
1162        let on_drag_end = Rc::new(move |app: &mut App, details: DragEndDetails| {
1163            self.handle_drag_end(app, details);
1164        });
1165        let widget = self.widget(app);
1166        let detector = GestureDetector::new()
1167            .behavior(widget.behavior)
1168            .drag_start_behavior(widget.drag_start_behavior)
1169            .child(content);
1170        if direction_is_x_axis {
1171            detector
1172                .on_horizontal_drag_start(on_drag_start)
1173                .on_horizontal_drag_update(on_drag_update)
1174                .on_horizontal_drag_end(on_drag_end)
1175                .into_widget()
1176        } else {
1177            detector
1178                .on_vertical_drag_start(on_drag_start)
1179                .on_vertical_drag_update(on_drag_update)
1180                .on_vertical_drag_end(on_drag_end)
1181                .into_widget()
1182        }
1183    }
1184}
1185
1186#[cfg(test)]
1187mod tests {
1188    use std::cell::{Cell, RefCell};
1189    use std::panic::{AssertUnwindSafe, catch_unwind};
1190
1191    use waft_embedder::Color;
1192    use waft_foundation::{Completer, ValueKey};
1193    use waft_painting::{AxisDirection, EdgeInsetsGeometry};
1194    use waft_rendering::{RenderBox, RenderClipRect, RenderCustomClip};
1195
1196    use super::*;
1197    use crate::framework::StatelessWidget;
1198    use crate::testing::{
1199        TestPointer, WidgetTester, expect, find, finds_nothing, finds_one_widget, test_widgets,
1200    };
1201    use crate::widgets::basic::{AspectRatio, Center, Column, Listener, StatefulBuilder};
1202    use crate::widgets::container::Container;
1203    use crate::widgets::scroll_controller::{ScrollController, ScrollControllerLeaf};
1204    use crate::widgets::scroll_physics::{NeverScrollableScrollPhysics, ScrollPhysicsRef};
1205    use crate::widgets::scroll_view::ListView;
1206    use crate::widgets::text::Text;
1207
1208    // ---- the test's own `buildTest` and its globals ----
1209
1210    const DEFAULT_DISMISS_DIRECTION: DismissDirection = DismissDirection::Horizontal;
1211    const CROSS_AXIS_END_OFFSET: f64 = 0.5;
1212
1213    /// The test's results: Dart's top-level variables, reset for each test.
1214    struct Results {
1215        reported_dismiss_update_reached: Cell<bool>,
1216        reported_dismiss_update_previous_reached: Cell<bool>,
1217        reported_dismiss_update_progress: Cell<f64>,
1218        reported_dismiss_update_reached_direction: Cell<Option<DismissDirection>>,
1219        reported_dismiss_direction: Cell<DismissDirection>,
1220        dismissed_items: RefCell<Vec<i64>>,
1221    }
1222
1223    impl Results {
1224        fn new() -> Rc<Results> {
1225            Rc::new(Results {
1226                reported_dismiss_update_reached: Cell::new(false),
1227                reported_dismiss_update_previous_reached: Cell::new(false),
1228                reported_dismiss_update_progress: Cell::new(0.0),
1229                reported_dismiss_update_reached_direction: Cell::new(None),
1230                reported_dismiss_direction: Cell::new(DEFAULT_DISMISS_DIRECTION),
1231                dismissed_items: RefCell::new(Vec::new()),
1232            })
1233        }
1234
1235        fn dismissed_items(&self) -> Vec<i64> {
1236            self.dismissed_items.borrow().clone()
1237        }
1238    }
1239
1240    /// `buildTest`'s named arguments.
1241    struct BuildTest {
1242        scroll_direction: Axis,
1243        dismiss_direction: DismissDirection,
1244        start_to_end_threshold: Option<f64>,
1245        text_direction: TextDirection,
1246        confirm_dismiss: Option<ConfirmDismissCallback>,
1247        controller: Option<Ref<ScrollController>>,
1248        scroll_physics: Option<ScrollPhysicsRef>,
1249        background: Option<&'static str>,
1250    }
1251
1252    impl Default for BuildTest {
1253        fn default() -> BuildTest {
1254            BuildTest {
1255                scroll_direction: Axis::Vertical,
1256                dismiss_direction: DEFAULT_DISMISS_DIRECTION,
1257                start_to_end_threshold: None,
1258                text_direction: TextDirection::Ltr,
1259                confirm_dismiss: None,
1260                controller: None,
1261                scroll_physics: None,
1262                background: None,
1263            }
1264        }
1265    }
1266
1267    fn build_test(results: &Rc<Results>, options: BuildTest) -> WidgetRef {
1268        let results = Rc::clone(results);
1269        let options = Rc::new(options);
1270        Directionality::new(
1271            options.text_direction,
1272            StatefulBuilder::new(move |_app, _context, set_state| {
1273                let build_dismissible_item = |item: i64| {
1274                    let results_dismissed = Rc::clone(&results);
1275                    let results_resize = Rc::clone(&results);
1276                    let results_update = Rc::clone(&results);
1277                    let set_state = Rc::clone(&set_state);
1278                    let mut thresholds = HashMap::new();
1279                    if let Some(threshold) = options.start_to_end_threshold {
1280                        thresholds.insert(DismissDirection::StartToEnd, threshold);
1281                    }
1282                    let mut dismissible = Dismissible::new(
1283                        ValueKey::new(item).into(),
1284                        SizedBox::new()
1285                            .width(100.0)
1286                            .height(100.0)
1287                            .child(Text::new(item.to_string())),
1288                    )
1289                    .drag_start_behavior(DragStartBehavior::Down)
1290                    .direction(options.dismiss_direction)
1291                    .on_dismissed(move |app, direction| {
1292                        let results = Rc::clone(&results_dismissed);
1293                        set_state(app, &mut move |_app| {
1294                            results.reported_dismiss_direction.set(direction);
1295                            assert!(!results.dismissed_items.borrow().contains(&item));
1296                            results.dismissed_items.borrow_mut().push(item);
1297                        });
1298                    })
1299                    .on_resize(move |_app| {
1300                        assert!(!results_resize.dismissed_items.borrow().contains(&item));
1301                    })
1302                    .on_update(move |_app, details| {
1303                        let results = &results_update;
1304                        results
1305                            .reported_dismiss_update_reached_direction
1306                            .set(Some(details.direction));
1307                        results.reported_dismiss_update_reached.set(details.reached);
1308                        results
1309                            .reported_dismiss_update_previous_reached
1310                            .set(details.previous_reached);
1311                        results
1312                            .reported_dismiss_update_progress
1313                            .set(details.progress);
1314                    })
1315                    .dismiss_thresholds(thresholds)
1316                    .cross_axis_end_offset(CROSS_AXIS_END_OFFSET);
1317                    if let Some(confirm_dismiss) = options.confirm_dismiss.clone() {
1318                        dismissible = dismissible
1319                            .confirm_dismiss(move |app, direction| confirm_dismiss(app, direction));
1320                    }
1321                    if let Some(background) = options.background {
1322                        dismissible = dismissible.background(Text::new(background));
1323                    }
1324                    dismissible.into_widget()
1325                };
1326
1327                let dismissed_items = results.dismissed_items();
1328                let mut list = ListView::new()
1329                    .drag_start_behavior(DragStartBehavior::Down)
1330                    .scroll_direction(options.scroll_direction)
1331                    .item_extent(100.0)
1332                    .children(
1333                        (0..9)
1334                            .filter(|item| !dismissed_items.contains(item))
1335                            .map(build_dismissible_item)
1336                            .collect::<Vec<_>>(),
1337                    );
1338                if let Some(physics) = options.scroll_physics.clone() {
1339                    list = list.physics(physics);
1340                }
1341                if let Some(controller) = &options.controller {
1342                    list = list.controller(controller.erase());
1343                }
1344                Container::new()
1345                    .padding(EdgeInsetsGeometry::all(10.0))
1346                    .child(list)
1347                    .into_widget()
1348            }),
1349        )
1350        .into_widget()
1351    }
1352
1353    /// The test's `dismissElement`: a drag from one edge of the text to the other.
1354    fn dismiss_element(tester: &mut WidgetTester, text: &str, gesture_direction: AxisDirection) {
1355        let (down_location, up_location) = match gesture_direction {
1356            AxisDirection::Left => (
1357                // getTopRight() returns a point that's just beyond itemWidget's right
1358                // edge and outside the Dismissible event listener's bounds.
1359                tester.get_top_right(find::text(text)) + Offset::new(-0.1, 0.0),
1360                tester.get_top_left(find::text(text)) + Offset::new(-0.1, 0.0),
1361            ),
1362            AxisDirection::Right => (
1363                // we do the same thing here to keep the test symmetric
1364                tester.get_top_left(find::text(text)) + Offset::new(0.1, 0.0),
1365                tester.get_top_right(find::text(text)) + Offset::new(0.1, 0.0),
1366            ),
1367            AxisDirection::Up => (
1368                // getBottomLeft() returns a point that's just below itemWidget's bottom
1369                // edge and outside the Dismissible event listener's bounds.
1370                tester.get_bottom_left(find::text(text)) + Offset::new(0.0, -0.1),
1371                tester.get_top_left(find::text(text)) + Offset::new(0.0, -0.1),
1372            ),
1373            AxisDirection::Down => (
1374                // again with doing the same here for symmetry
1375                tester.get_top_left(find::text(text)) + Offset::new(0.1, 0.0),
1376                tester.get_bottom_left(find::text(text)) + Offset::new(0.1, 0.0),
1377            ),
1378        };
1379
1380        let mut gesture = TestPointer::touch(1);
1381        tester.down(&mut gesture, down_location);
1382        tester.move_to(&mut gesture, up_location, true);
1383        tester.up(&gesture);
1384    }
1385
1386    fn axis_delta(gesture_direction: AxisDirection, amount: f64) -> Offset {
1387        match gesture_direction {
1388            AxisDirection::Left => Offset::new(-amount, 0.0),
1389            AxisDirection::Right => Offset::new(amount, 0.0),
1390            AxisDirection::Up => Offset::new(0.0, -amount),
1391            AxisDirection::Down => Offset::new(0.0, amount),
1392        }
1393    }
1394
1395    /// The test's `flingElement`.
1396    fn fling_element(tester: &mut WidgetTester, text: &str, gesture_direction: AxisDirection) {
1397        let delta = axis_delta(gesture_direction, 300.0);
1398        tester.fling(find::text(text), delta, 1000.0);
1399    }
1400
1401    /// The test's `flingElementFromZero`: a drag one way, then a fling back to where it
1402    /// started.
1403    fn fling_element_from_zero(
1404        tester: &mut WidgetTester,
1405        text: &str,
1406        gesture_direction: AxisDirection,
1407    ) {
1408        let delta = axis_delta(gesture_direction, 300.0);
1409        let start = tester.get_center(find::text(text));
1410        let pointer = tester.next_pointer();
1411        tester.fling_from_after(
1412            start,
1413            delta,
1414            1000.0,
1415            pointer,
1416            delta * -1.0,
1417            Duration::from_secs(1),
1418        );
1419    }
1420
1421    /// The test's `rollbackElement`.
1422    fn rollback_element(tester: &mut WidgetTester, text: &str, gesture_direction: AxisDirection) {
1423        let delta = axis_delta(gesture_direction, 30.0);
1424        tester.fling(find::text(text), delta, 1000.0);
1425    }
1426
1427    type DismissMethod = fn(&mut WidgetTester, &str, AxisDirection);
1428
1429    fn dismiss_item(
1430        tester: &mut WidgetTester,
1431        item: i64,
1432        gesture_direction: AxisDirection,
1433        mechanism: DismissMethod,
1434    ) {
1435        let text = item.to_string();
1436        expect(tester, &find::text(&text), finds_one_widget());
1437
1438        mechanism(tester, &text, gesture_direction);
1439        tester.pump_and_settle();
1440    }
1441
1442    fn drag_item(
1443        tester: &mut WidgetTester,
1444        item: i64,
1445        gesture_direction: AxisDirection,
1446        amount: f64,
1447    ) {
1448        let text = item.to_string();
1449        expect(tester, &find::text(&text), finds_one_widget());
1450
1451        tester.drag(find::text(&text), axis_delta(gesture_direction, amount));
1452        tester.pump();
1453    }
1454
1455    fn check_fling_item_before_movement_end(
1456        tester: &mut WidgetTester,
1457        item: i64,
1458        gesture_direction: AxisDirection,
1459        mechanism: DismissMethod,
1460    ) {
1461        let text = item.to_string();
1462        expect(tester, &find::text(&text), finds_one_widget());
1463
1464        mechanism(tester, &text, gesture_direction);
1465
1466        tester.pump(); // start the slide
1467        tester.pump_by(Duration::from_millis(100));
1468    }
1469
1470    fn check_fling_item_after_movement(
1471        tester: &mut WidgetTester,
1472        item: i64,
1473        gesture_direction: AxisDirection,
1474        mechanism: DismissMethod,
1475    ) {
1476        let text = item.to_string();
1477        expect(tester, &find::text(&text), finds_one_widget());
1478
1479        mechanism(tester, &text, gesture_direction);
1480
1481        tester.pump(); // start the slide
1482        tester.pump_by(Duration::from_millis(300));
1483    }
1484
1485    /// The test's `Test1215DismissibleWidget`.
1486    #[derive(Debug)]
1487    struct Test1215DismissibleWidget(&'static str);
1488
1489    impl StatelessWidget for Test1215DismissibleWidget {
1490        fn build(&self, _app: &mut App, _context: BuildContext) -> WidgetRef {
1491            Dismissible::new(
1492                ValueKey::new(self.0).into(),
1493                AspectRatio::new(1.0).child(Text::new(self.0)),
1494            )
1495            .drag_start_behavior(DragStartBehavior::Down)
1496            .into_widget()
1497        }
1498    }
1499
1500    /// A `confirmDismiss` that records the direction it was asked about and answers `value`.
1501    fn confirm_with(
1502        value: Option<bool>,
1503        confirm_dismiss_direction: &Rc<Cell<Option<DismissDirection>>>,
1504    ) -> ConfirmDismissCallback {
1505        let confirm_dismiss_direction = Rc::clone(confirm_dismiss_direction);
1506        Rc::new(move |_app, direction| {
1507            confirm_dismiss_direction.set(Some(direction));
1508            Task::ready(value)
1509        })
1510    }
1511
1512    /// A `confirmDismiss` that answers what `completer` completes with.
1513    fn confirm_by(completer: &Rc<RefCell<Completer<Option<bool>>>>) -> ConfirmDismissCallback {
1514        let completer = Rc::clone(completer);
1515        Rc::new(move |app, _direction| {
1516            let future = completer.borrow().future();
1517            app.spawn(async move |_cx| future.await)
1518        })
1519    }
1520
1521    use AxisDirection::{Down as AxisDown, Left, Right, Up as AxisUp};
1522
1523    #[test]
1524    fn a_horizontal_drag_dismisses_in_a_vertical_list() {
1525        test_widgets(|tester| {
1526            let results = Results::new();
1527            tester.pump_widget(build_test(&results, BuildTest::default()));
1528            assert!(results.dismissed_items().is_empty());
1529
1530            dismiss_item(tester, 0, Right, dismiss_element);
1531            expect(tester, &find::text("0"), finds_nothing());
1532            assert_eq!(results.dismissed_items(), [0]);
1533            assert_eq!(
1534                results.reported_dismiss_direction.get(),
1535                DismissDirection::StartToEnd
1536            );
1537
1538            dismiss_item(tester, 1, Left, dismiss_element);
1539            expect(tester, &find::text("1"), finds_nothing());
1540            assert_eq!(results.dismissed_items(), [0, 1]);
1541            assert_eq!(
1542                results.reported_dismiss_direction.get(),
1543                DismissDirection::EndToStart
1544            );
1545        });
1546    }
1547
1548    #[test]
1549    fn a_horizontal_fling_dismisses_in_a_vertical_list() {
1550        test_widgets(|tester| {
1551            let results = Results::new();
1552            tester.pump_widget(build_test(&results, BuildTest::default()));
1553            assert!(results.dismissed_items().is_empty());
1554
1555            dismiss_item(tester, 0, Right, fling_element);
1556            expect(tester, &find::text("0"), finds_nothing());
1557            assert_eq!(results.dismissed_items(), [0]);
1558            assert_eq!(
1559                results.reported_dismiss_direction.get(),
1560                DismissDirection::StartToEnd
1561            );
1562
1563            dismiss_item(tester, 1, Left, fling_element);
1564            expect(tester, &find::text("1"), finds_nothing());
1565            assert_eq!(results.dismissed_items(), [0, 1]);
1566            assert_eq!(
1567                results.reported_dismiss_direction.get(),
1568                DismissDirection::EndToStart
1569            );
1570        });
1571    }
1572
1573    #[test]
1574    fn a_horizontal_fling_does_not_dismiss_at_zero_offset_but_does_otherwise() {
1575        test_widgets(|tester| {
1576            let results = Results::new();
1577            tester.pump_widget(build_test(
1578                &results,
1579                BuildTest {
1580                    start_to_end_threshold: Some(0.95),
1581                    ..BuildTest::default()
1582                },
1583            ));
1584            assert!(results.dismissed_items().is_empty());
1585
1586            dismiss_item(tester, 0, Right, fling_element_from_zero);
1587            expect(tester, &find::text("0"), finds_one_widget());
1588            assert!(results.dismissed_items().is_empty());
1589
1590            dismiss_item(tester, 0, Left, fling_element_from_zero);
1591            expect(tester, &find::text("0"), finds_one_widget());
1592            assert!(results.dismissed_items().is_empty());
1593
1594            dismiss_item(tester, 0, Right, fling_element);
1595            expect(tester, &find::text("0"), finds_nothing());
1596            assert_eq!(results.dismissed_items(), [0]);
1597            assert_eq!(
1598                results.reported_dismiss_direction.get(),
1599                DismissDirection::StartToEnd
1600            );
1601
1602            dismiss_item(tester, 1, Left, fling_element);
1603            expect(tester, &find::text("1"), finds_nothing());
1604            assert_eq!(results.dismissed_items(), [0, 1]);
1605            assert_eq!(
1606                results.reported_dismiss_direction.get(),
1607                DismissDirection::EndToStart
1608            );
1609        });
1610    }
1611
1612    #[test]
1613    fn a_vertical_drag_dismisses_in_a_horizontal_list() {
1614        test_widgets(|tester| {
1615            let results = Results::new();
1616            tester.pump_widget(build_test(
1617                &results,
1618                BuildTest {
1619                    scroll_direction: Axis::Horizontal,
1620                    dismiss_direction: DismissDirection::Vertical,
1621                    ..BuildTest::default()
1622                },
1623            ));
1624            assert!(results.dismissed_items().is_empty());
1625
1626            dismiss_item(tester, 0, AxisUp, dismiss_element);
1627            expect(tester, &find::text("0"), finds_nothing());
1628            assert_eq!(results.dismissed_items(), [0]);
1629            assert_eq!(
1630                results.reported_dismiss_direction.get(),
1631                DismissDirection::Up
1632            );
1633
1634            dismiss_item(tester, 1, AxisDown, dismiss_element);
1635            expect(tester, &find::text("1"), finds_nothing());
1636            assert_eq!(results.dismissed_items(), [0, 1]);
1637            assert_eq!(
1638                results.reported_dismiss_direction.get(),
1639                DismissDirection::Down
1640            );
1641        });
1642    }
1643
1644    /// The shape of the four one-direction cases: the wrong way first, which leaves the item,
1645    /// then the right way, which dismisses it.
1646    fn check_one_way(
1647        options: fn() -> BuildTest,
1648        mechanism: DismissMethod,
1649        wrong_way: AxisDirection,
1650        right_way: AxisDirection,
1651        also_item_one: bool,
1652    ) {
1653        test_widgets(|tester| {
1654            check_one_way_with(
1655                tester,
1656                options(),
1657                mechanism,
1658                wrong_way,
1659                right_way,
1660                also_item_one,
1661            )
1662        });
1663    }
1664
1665    fn check_one_way_with(
1666        tester: &mut WidgetTester,
1667        options: BuildTest,
1668        mechanism: DismissMethod,
1669        wrong_way: AxisDirection,
1670        right_way: AxisDirection,
1671        also_item_one: bool,
1672    ) {
1673        let results = Results::new();
1674        tester.pump_widget(build_test(&results, options));
1675        assert!(results.dismissed_items().is_empty());
1676
1677        dismiss_item(tester, 0, wrong_way, mechanism);
1678        expect(tester, &find::text("0"), finds_one_widget());
1679        assert!(results.dismissed_items().is_empty());
1680        if also_item_one {
1681            dismiss_item(tester, 1, wrong_way, mechanism);
1682        }
1683
1684        dismiss_item(tester, 0, right_way, mechanism);
1685        expect(tester, &find::text("0"), finds_nothing());
1686        assert_eq!(results.dismissed_items(), [0]);
1687        if also_item_one {
1688            dismiss_item(tester, 1, right_way, mechanism);
1689        }
1690    }
1691
1692    #[test]
1693    fn a_drag_left_dismisses_with_end_to_start_in_ltr() {
1694        check_one_way(
1695            || BuildTest {
1696                dismiss_direction: DismissDirection::EndToStart,
1697                ..BuildTest::default()
1698            },
1699            dismiss_element,
1700            Right,
1701            Left,
1702            true,
1703        );
1704    }
1705
1706    #[test]
1707    fn a_drag_right_dismisses_with_start_to_end_in_ltr() {
1708        check_one_way(
1709            || BuildTest {
1710                dismiss_direction: DismissDirection::StartToEnd,
1711                ..BuildTest::default()
1712            },
1713            dismiss_element,
1714            Left,
1715            Right,
1716            false,
1717        );
1718    }
1719
1720    #[test]
1721    fn a_drag_right_dismisses_with_end_to_start_in_rtl() {
1722        check_one_way(
1723            || BuildTest {
1724                text_direction: TextDirection::Rtl,
1725                dismiss_direction: DismissDirection::EndToStart,
1726                ..BuildTest::default()
1727            },
1728            dismiss_element,
1729            Left,
1730            Right,
1731            false,
1732        );
1733    }
1734
1735    #[test]
1736    fn a_drag_left_dismisses_with_start_to_end_in_rtl() {
1737        check_one_way(
1738            || BuildTest {
1739                text_direction: TextDirection::Rtl,
1740                dismiss_direction: DismissDirection::StartToEnd,
1741                ..BuildTest::default()
1742            },
1743            dismiss_element,
1744            Right,
1745            Left,
1746            true,
1747        );
1748    }
1749
1750    #[test]
1751    fn a_fling_left_dismisses_with_end_to_start_in_ltr() {
1752        // Flutter's case drags rather than flings, as written.
1753        check_one_way(
1754            || BuildTest {
1755                dismiss_direction: DismissDirection::EndToStart,
1756                ..BuildTest::default()
1757            },
1758            dismiss_element,
1759            Right,
1760            Left,
1761            true,
1762        );
1763    }
1764
1765    #[test]
1766    fn a_fling_right_dismisses_with_start_to_end_in_ltr() {
1767        check_one_way(
1768            || BuildTest {
1769                dismiss_direction: DismissDirection::StartToEnd,
1770                ..BuildTest::default()
1771            },
1772            fling_element,
1773            Left,
1774            Right,
1775            false,
1776        );
1777    }
1778
1779    #[test]
1780    fn a_fling_right_dismisses_with_end_to_start_in_rtl() {
1781        check_one_way(
1782            || BuildTest {
1783                text_direction: TextDirection::Rtl,
1784                dismiss_direction: DismissDirection::EndToStart,
1785                ..BuildTest::default()
1786            },
1787            fling_element,
1788            Left,
1789            Right,
1790            false,
1791        );
1792    }
1793
1794    #[test]
1795    fn a_fling_left_dismisses_with_start_to_end_in_rtl() {
1796        check_one_way(
1797            || BuildTest {
1798                text_direction: TextDirection::Rtl,
1799                dismiss_direction: DismissDirection::StartToEnd,
1800                ..BuildTest::default()
1801            },
1802            fling_element,
1803            Right,
1804            Left,
1805            true,
1806        );
1807    }
1808
1809    #[test]
1810    fn a_drag_up_dismisses_with_up() {
1811        check_one_way(
1812            || BuildTest {
1813                scroll_direction: Axis::Horizontal,
1814                dismiss_direction: DismissDirection::Up,
1815                ..BuildTest::default()
1816            },
1817            dismiss_element,
1818            AxisDown,
1819            AxisUp,
1820            false,
1821        );
1822    }
1823
1824    #[test]
1825    fn a_drag_down_dismisses_with_down() {
1826        check_one_way(
1827            || BuildTest {
1828                scroll_direction: Axis::Horizontal,
1829                dismiss_direction: DismissDirection::Down,
1830                ..BuildTest::default()
1831            },
1832            dismiss_element,
1833            AxisUp,
1834            AxisDown,
1835            false,
1836        );
1837    }
1838
1839    #[test]
1840    fn a_fling_up_dismisses_with_up() {
1841        check_one_way(
1842            || BuildTest {
1843                scroll_direction: Axis::Horizontal,
1844                dismiss_direction: DismissDirection::Up,
1845                ..BuildTest::default()
1846            },
1847            fling_element,
1848            AxisDown,
1849            AxisUp,
1850            false,
1851        );
1852    }
1853
1854    #[test]
1855    fn a_fling_down_dismisses_with_down() {
1856        check_one_way(
1857            || BuildTest {
1858                scroll_direction: Axis::Horizontal,
1859                dismiss_direction: DismissDirection::Down,
1860                ..BuildTest::default()
1861            },
1862            fling_element,
1863            AxisUp,
1864            AxisDown,
1865            false,
1866        );
1867    }
1868
1869    #[test]
1870    fn a_drag_left_has_no_effect_with_a_high_dismiss_threshold() {
1871        check_one_way(
1872            || BuildTest {
1873                start_to_end_threshold: Some(1.0),
1874                ..BuildTest::default()
1875            },
1876            dismiss_element,
1877            Right,
1878            Left,
1879            false,
1880        );
1881    }
1882
1883    #[test]
1884    fn a_fling_left_has_no_effect_with_a_high_dismiss_threshold() {
1885        check_one_way(
1886            || BuildTest {
1887                start_to_end_threshold: Some(1.0),
1888                ..BuildTest::default()
1889            },
1890            fling_element,
1891            Right,
1892            Left,
1893            false,
1894        );
1895    }
1896
1897    #[test]
1898    fn drag_moves_across_rebuilds_do_not_assert() {
1899        test_widgets(|tester| {
1900            let results = Results::new();
1901            tester.pump_widget(build_test(
1902                &results,
1903                BuildTest {
1904                    scroll_direction: Axis::Horizontal,
1905                    dismiss_direction: DismissDirection::Down,
1906                    ..BuildTest::default()
1907                },
1908            ));
1909            let location = tester.get_top_left(find::text("0"));
1910            let offset = Offset::new(0.0, 5.0);
1911            let mut gesture = TestPointer::touch(1);
1912            tester.down(&mut gesture, location);
1913            for _ in 0..4 {
1914                tester.move_by(&mut gesture, offset, true);
1915                tester.pump_widget(build_test(&results, BuildTest::default()));
1916            }
1917            tester.up(&gesture);
1918        });
1919    }
1920
1921    #[test]
1922    fn dismissing_the_bottom_then_the_top_item_does_not_throw() {
1923        test_widgets(|tester| {
1924            tester.pump_widget(
1925                Directionality::new(
1926                    TextDirection::Ltr,
1927                    Center::new().child(SizedBox::new().width(100.0).height(1000.0).child(
1928                        Column::new().children([
1929                            Test1215DismissibleWidget("1").into_widget(),
1930                            Test1215DismissibleWidget("2").into_widget(),
1931                        ]),
1932                    )),
1933                )
1934                .into_widget(),
1935            );
1936            expect(tester, &find::text("1"), finds_one_widget());
1937            expect(tester, &find::text("2"), finds_one_widget());
1938            dismiss_element(tester, "2", Right);
1939            tester.pump(); // start the slide away
1940            tester.pump_by(Duration::from_secs(1)); // finish the slide away
1941            expect(tester, &find::text("1"), finds_one_widget());
1942            expect(tester, &find::text("2"), finds_nothing());
1943            dismiss_element(tester, "1", Right);
1944            tester.pump(); // start the slide away
1945            // finish the slide away (at which point the child is no longer included in the tree)
1946            tester.pump_by(Duration::from_secs(1));
1947            expect(tester, &find::text("1"), finds_nothing());
1948            expect(tester, &find::text("2"), finds_nothing());
1949        });
1950    }
1951
1952    #[test]
1953    fn a_dismissible_collapses_from_its_full_size() {
1954        test_widgets(|tester| {
1955            let results = Results::new();
1956            tester.pump_widget(build_test(
1957                &results,
1958                BuildTest {
1959                    background: Some("background"),
1960                    ..BuildTest::default()
1961                },
1962            ));
1963            assert!(results.dismissed_items().is_empty());
1964
1965            expect(tester, &find::text("0"), finds_one_widget());
1966            dismiss_element(tester, "0", Right);
1967            tester.pump();
1968
1969            // The other four have been culled.
1970            expect(tester, &find::text("background"), finds_one_widget());
1971            assert_eq!(tester.get_size(find::text("background")).height(), 100.0);
1972        });
1973    }
1974
1975    // ---- not in dismissible_test.dart: `_DismissibleClipper` ----
1976
1977    #[test]
1978    fn the_background_is_clipped_to_the_part_the_child_has_uncovered() {
1979        test_widgets(|tester| {
1980            let results = Results::new();
1981            tester.pump_widget(build_test(
1982                &results,
1983                BuildTest {
1984                    background: Some("background"),
1985                    ..BuildTest::default()
1986                },
1987            ));
1988            let start = tester.get_center(find::text("0"));
1989            let mut gesture = TestPointer::touch(1);
1990            tester.down(&mut gesture, start);
1991            tester.move_by(&mut gesture, Offset::new(-30.0, 0.0), true);
1992            tester.pump();
1993
1994            let background = tester.render_object(find::text("background"));
1995            let app = tester.cell.borrow();
1996            let mut clip = None;
1997            let mut ancestor = background.parent(&app);
1998            while let Some(object) = ancestor {
1999                if let Some(clip_rect) = object.downcast::<RenderClipRect>(&app) {
2000                    clip = Some(clip_rect);
2001                    break;
2002                }
2003                ancestor = object.parent(&app);
2004            }
2005            let clip = clip.expect("the background sits in a ClipRect");
2006            let width = clip.size(&app).width();
2007            assert_eq!(
2008                RenderCustomClip::<Rect>::clip(clip, &app),
2009                Rect::from_ltrb(width - 30.0, 0.0, width, 100.0)
2010            );
2011            drop(app);
2012            tester.up(&gesture);
2013        });
2014    }
2015
2016    #[test]
2017    fn a_fling_item_stays_before_the_movement_duration_completes() {
2018        test_widgets(|tester| {
2019            let results = Results::new();
2020            tester.pump_widget(build_test(&results, BuildTest::default()));
2021            assert!(results.dismissed_items().is_empty());
2022
2023            check_fling_item_before_movement_end(tester, 0, Left, fling_element);
2024            expect(tester, &find::text("0"), finds_one_widget());
2025
2026            check_fling_item_before_movement_end(tester, 1, Right, fling_element);
2027            expect(tester, &find::text("1"), finds_one_widget());
2028        });
2029    }
2030
2031    #[test]
2032    fn a_fling_item_is_gone_after_the_movement_duration() {
2033        test_widgets(|tester| {
2034            let results = Results::new();
2035            tester.pump_widget(build_test(&results, BuildTest::default()));
2036            assert!(results.dismissed_items().is_empty());
2037
2038            check_fling_item_after_movement(tester, 1, Left, fling_element);
2039            // The resize starts after the `await` on the confirmation, which runs at the next
2040            // checkpoint rather than among the frame's microtasks (waft-foundation's `Task`
2041            // entry), so the child is gone a frame later than in Flutter.
2042            tester.pump();
2043            expect(tester, &find::text("1"), finds_nothing());
2044
2045            check_fling_item_after_movement(tester, 0, Right, fling_element);
2046            // The resize starts after the `await` on the confirmation, which runs at the next
2047            // checkpoint rather than among the frame's microtasks (waft-foundation's `Task`
2048            // entry), so the child is gone a frame later than in Flutter.
2049            tester.pump();
2050            expect(tester, &find::text("0"), finds_nothing());
2051        });
2052    }
2053
2054    #[test]
2055    fn a_horizontal_fling_short_of_the_threshold_rolls_back() {
2056        test_widgets(|tester| {
2057            let results = Results::new();
2058            tester.pump_widget(build_test(
2059                &results,
2060                BuildTest {
2061                    scroll_direction: Axis::Horizontal,
2062                    ..BuildTest::default()
2063                },
2064            ));
2065            assert!(results.dismissed_items().is_empty());
2066
2067            check_fling_item_after_movement(tester, 0, Left, rollback_element);
2068            expect(tester, &find::text("0"), finds_one_widget());
2069            assert!(results.dismissed_items().is_empty());
2070
2071            check_fling_item_after_movement(tester, 1, Right, rollback_element);
2072            expect(tester, &find::text("1"), finds_one_widget());
2073            assert!(results.dismissed_items().is_empty());
2074        });
2075    }
2076
2077    #[test]
2078    fn a_vertical_fling_short_of_the_threshold_rolls_back() {
2079        test_widgets(|tester| {
2080            let results = Results::new();
2081            tester.pump_widget(build_test(&results, BuildTest::default()));
2082            assert!(results.dismissed_items().is_empty());
2083
2084            check_fling_item_after_movement(tester, 0, Left, rollback_element);
2085            expect(tester, &find::text("0"), finds_one_widget());
2086            assert!(results.dismissed_items().is_empty());
2087
2088            check_fling_item_after_movement(tester, 1, Right, rollback_element);
2089            expect(tester, &find::text("1"), finds_one_widget());
2090            assert!(results.dismissed_items().is_empty());
2091        });
2092    }
2093
2094    #[test]
2095    fn confirm_dismiss_answers_true_false_and_none() {
2096        test_widgets(|tester| {
2097            let results = Results::new();
2098            let confirm_dismiss_direction = Rc::new(Cell::new(None));
2099            let build_frame = |value: Option<bool>| {
2100                build_test(
2101                    &results,
2102                    BuildTest {
2103                        confirm_dismiss: Some(confirm_with(value, &confirm_dismiss_direction)),
2104                        ..BuildTest::default()
2105                    },
2106                )
2107            };
2108
2109            // Dismiss is confirmed IFF confirmDismiss() returns true.
2110            tester.pump_widget(build_frame(Some(true)));
2111            assert!(results.dismissed_items().is_empty());
2112
2113            dismiss_item(tester, 0, Right, fling_element);
2114            expect(tester, &find::text("0"), finds_nothing());
2115            assert_eq!(results.dismissed_items(), [0]);
2116            assert_eq!(
2117                results.reported_dismiss_direction.get(),
2118                DismissDirection::StartToEnd
2119            );
2120            assert_eq!(
2121                confirm_dismiss_direction.get(),
2122                Some(DismissDirection::StartToEnd)
2123            );
2124
2125            dismiss_item(tester, 1, Left, fling_element);
2126            expect(tester, &find::text("1"), finds_nothing());
2127            assert_eq!(results.dismissed_items(), [0, 1]);
2128            assert_eq!(
2129                results.reported_dismiss_direction.get(),
2130                DismissDirection::EndToStart
2131            );
2132            assert_eq!(
2133                confirm_dismiss_direction.get(),
2134                Some(DismissDirection::EndToStart)
2135            );
2136
2137            for value in [Some(false), None] {
2138                // Dismiss is not confirmed if confirmDismiss() returns false or null.
2139                results.dismissed_items.borrow_mut().clear();
2140                tester.pump_widget(build_frame(value));
2141
2142                dismiss_item(tester, 0, Right, fling_element);
2143                expect(tester, &find::text("0"), finds_one_widget());
2144                assert!(results.dismissed_items().is_empty());
2145                assert_eq!(
2146                    confirm_dismiss_direction.get(),
2147                    Some(DismissDirection::StartToEnd)
2148                );
2149
2150                dismiss_item(tester, 1, Left, fling_element);
2151                expect(tester, &find::text("1"), finds_one_widget());
2152                assert!(results.dismissed_items().is_empty());
2153                assert_eq!(
2154                    confirm_dismiss_direction.get(),
2155                    Some(DismissDirection::EndToStart)
2156                );
2157            }
2158        });
2159    }
2160
2161    #[test]
2162    fn a_pending_confirm_dismiss_does_not_cause_errors() {
2163        test_widgets(|tester| {
2164            let results = Results::new();
2165            let completer = Rc::new(RefCell::new(Completer::new()));
2166            let build_frame = |completer: &Rc<RefCell<Completer<Option<bool>>>>| {
2167                *completer.borrow_mut() = Completer::new();
2168                build_test(
2169                    &results,
2170                    BuildTest {
2171                        confirm_dismiss: Some(confirm_by(completer)),
2172                        ..BuildTest::default()
2173                    },
2174                )
2175            };
2176
2177            // false and true for _handleDragEnd - when dragged to the end and released, then false
2178            // and true for _handleDismissStatusChanged - when fling reaches the end.
2179            for (mechanism, answer) in [
2180                (dismiss_element as DismissMethod, false),
2181                (dismiss_element, true),
2182                (fling_element, false),
2183                (fling_element, true),
2184            ] {
2185                tester.pump_widget(build_frame(&completer));
2186
2187                dismiss_item(tester, 0, Right, mechanism);
2188                expect(tester, &find::text("0"), finds_one_widget());
2189                assert!(results.dismissed_items().is_empty());
2190
2191                tester.pump_widget(SizedBox::new().into_widget());
2192                completer
2193                    .borrow()
2194                    .complete(&mut tester.cell.borrow_mut(), Some(answer));
2195                tester.pump();
2196            }
2197        });
2198    }
2199
2200    #[test]
2201    fn a_dismissible_cannot_be_dragged_while_confirm_dismiss_is_pending() {
2202        test_widgets(|tester| {
2203            let results = Results::new();
2204            let completer = Rc::new(RefCell::new(Completer::new()));
2205            tester.pump_widget(build_test(
2206                &results,
2207                BuildTest {
2208                    confirm_dismiss: Some(confirm_by(&completer)),
2209                    ..BuildTest::default()
2210                },
2211            ));
2212
2213            // Trigger confirmDismiss call.
2214            dismiss_item(tester, 0, Right, dismiss_element);
2215            let position = tester.get_top_left(find::text("0"));
2216
2217            // Try to move and verify it has not moved.
2218            let drag_at = Offset::new(100.0, tester.get_top_left(find::text("0")).dy());
2219            let mut gesture = TestPointer::touch(1);
2220            tester.down(&mut gesture, drag_at);
2221            tester.move_to(&mut gesture, drag_at + Offset::new(100.0, 0.0), true);
2222            tester.up(&gesture);
2223            tester.pump();
2224            assert_eq!(tester.get_top_left(find::text("0")), position);
2225        });
2226    }
2227
2228    #[test]
2229    fn an_item_dragged_to_the_end_comes_back_when_confirm_dismiss_answers_false() {
2230        test_widgets(|tester| {
2231            let results = Results::new();
2232            let completer = Rc::new(RefCell::new(Completer::new()));
2233            tester.pump_widget(build_test(
2234                &results,
2235                BuildTest {
2236                    confirm_dismiss: Some(confirm_by(&completer)),
2237                    ..BuildTest::default()
2238                },
2239            ));
2240
2241            let position = tester.get_top_left(find::text("0"));
2242            dismiss_item(tester, 0, Right, dismiss_element);
2243            completer
2244                .borrow()
2245                .complete(&mut tester.cell.borrow_mut(), Some(false));
2246            tester.pump_and_settle();
2247            assert_eq!(tester.get_top_left(find::text("0")), position);
2248        });
2249    }
2250
2251    #[test]
2252    fn a_null_resize_duration_calls_on_dismissed_at_once() {
2253        test_widgets(|tester| {
2254            let resized = Rc::new(Cell::new(false));
2255            let dismissed = Rc::new(Cell::new(false));
2256            let (on_resized, on_dismissed) = (Rc::clone(&resized), Rc::clone(&dismissed));
2257            tester.pump_widget(
2258                Directionality::new(
2259                    TextDirection::Ltr,
2260                    Dismissible::new(
2261                        waft_foundation::UniqueKey::new().into(),
2262                        SizedBox::new()
2263                            .width(100.0)
2264                            .height(100.0)
2265                            .child(Text::new("0")),
2266                    )
2267                    .drag_start_behavior(DragStartBehavior::Down)
2268                    .resize_duration(None)
2269                    .on_dismissed(move |_app, _direction| on_dismissed.set(true))
2270                    .on_resize(move |_app| on_resized.set(true)),
2271                )
2272                .into_widget(),
2273            );
2274
2275            dismiss_element(tester, "0", Right);
2276            tester.pump();
2277            assert!(dismissed.get());
2278            assert!(!resized.get());
2279        });
2280    }
2281
2282    /// Dart's case takes the error and ends; here the panic unwound the pump, and the tester
2283    /// leaves that half-built tree alone at its end (`testing/PORTING.md`).
2284    #[test]
2285    fn a_dismissed_dismissible_still_in_the_tree_panics() {
2286        test_widgets(|tester| {
2287            let results = Results::new();
2288            let on_dismissed_results = Rc::clone(&results);
2289            tester.pump_widget(
2290                Directionality::new(
2291                    TextDirection::Ltr,
2292                    StatefulBuilder::new(move |_app, _context, set_state| {
2293                        let results = Rc::clone(&on_dismissed_results);
2294                        ListView::new()
2295                            .drag_start_behavior(DragStartBehavior::Down)
2296                            .item_extent(100.0)
2297                            .children([Dismissible::new(
2298                                ValueKey::new(1i64).into(),
2299                                SizedBox::new()
2300                                    .width(100.0)
2301                                    .height(100.0)
2302                                    .child(Text::new(1.to_string())),
2303                            )
2304                            .drag_start_behavior(DragStartBehavior::Down)
2305                            .on_dismissed(move |app, direction| {
2306                                let results = Rc::clone(&results);
2307                                set_state(app, &mut move |_app| {
2308                                    results.reported_dismiss_direction.set(direction);
2309                                    assert!(!results.dismissed_items.borrow().contains(&1));
2310                                    results.dismissed_items.borrow_mut().push(1);
2311                                });
2312                            })
2313                            .cross_axis_end_offset(CROSS_AXIS_END_OFFSET)
2314                            .into_widget()])
2315                            .into_widget()
2316                    }),
2317                )
2318                .into_widget(),
2319            );
2320            assert!(results.dismissed_items().is_empty());
2321            let error = catch_unwind(AssertUnwindSafe(|| {
2322                dismiss_item(tester, 1, Right, dismiss_element)
2323            }))
2324            .expect_err("the rebuild that keeps the dismissed Dismissible panics");
2325            assert_eq!(results.dismissed_items(), [1]);
2326            let message = match error.downcast_ref::<&str>() {
2327                Some(message) => message.to_string(),
2328                None => error
2329                    .downcast_ref::<String>()
2330                    .expect("a panic message")
2331                    .clone(),
2332            };
2333            let mut lines = message.lines();
2334            assert_eq!(
2335                lines.next(),
2336                Some("A dismissed Dismissible widget is still part of the tree.")
2337            );
2338            // Dart's last diagnostic, the hint.
2339            assert_eq!(
2340                lines.next(),
2341                Some(
2342                    "Make sure to implement the onDismissed handler and to immediately remove the \
2343                     Dismissible widget from the application once that handler has fired."
2344                )
2345            );
2346            assert_eq!(lines.next(), None);
2347        });
2348    }
2349
2350    // ---- not in dismissible_test.dart: the constructor's background assert ----
2351
2352    fn backgrounds_test(dismissible: Dismissible) -> WidgetRef {
2353        Directionality::new(TextDirection::Ltr, dismissible).into_widget()
2354    }
2355
2356    fn backgrounds_item() -> Dismissible {
2357        Dismissible::new(
2358            waft_foundation::UniqueKey::new().into(),
2359            SizedBox::new().width(100.0).height(100.0),
2360        )
2361    }
2362
2363    #[test]
2364    fn a_secondary_background_may_be_given_before_the_background() {
2365        test_widgets(|tester| {
2366            tester.pump_widget(backgrounds_test(
2367                backgrounds_item()
2368                    .secondary_background(SizedBox::new())
2369                    .background(SizedBox::new()),
2370            ));
2371        });
2372    }
2373
2374    #[test]
2375    #[should_panic(expected = "self.secondary_background.is_none() || self.background.is_some()")]
2376    fn a_secondary_background_without_a_background_panics_when_made_a_widget() {
2377        backgrounds_item()
2378            .secondary_background(SizedBox::new())
2379            .into_widget();
2380    }
2381
2382    #[test]
2383    fn behavior_decides_how_the_dismissible_is_hit() {
2384        test_widgets(|tester| {
2385            let did_receive_pointer_down = Rc::new(Cell::new(false));
2386            let build_stack = |child: WidgetRef| {
2387                let received = Rc::clone(&did_receive_pointer_down);
2388                Directionality::new(
2389                    TextDirection::Ltr,
2390                    Stack::new().children([
2391                        Listener::new()
2392                            .on_pointer_down(Rc::new(move |_app, _event| received.set(true)))
2393                            .child(
2394                                Container::new()
2395                                    .width(100.0)
2396                                    .height(100.0)
2397                                    .color(Color::from_argb(0xFF, 0x00, 0xFF, 0x00)),
2398                            )
2399                            .into_widget(),
2400                        child,
2401                    ]),
2402                )
2403                .into_widget()
2404            };
2405            let dismissible = || {
2406                Dismissible::new(
2407                    ValueKey::new(1i64).into(),
2408                    SizedBox::new().width(100.0).height(100.0),
2409                )
2410            };
2411
2412            tester.pump_widget(build_stack(dismissible().into_widget()));
2413            tester.tap_at(Offset::new(10.0, 10.0), 1);
2414            assert!(!did_receive_pointer_down.get());
2415
2416            for (behavior, received) in [
2417                (HitTestBehavior::DeferToChild, true),
2418                (HitTestBehavior::Opaque, false),
2419                (HitTestBehavior::Translucent, true),
2420            ] {
2421                did_receive_pointer_down.set(false);
2422                tester.pump_widget(build_stack(dismissible().behavior(behavior).into_widget()));
2423                tester.tap_at(Offset::new(10.0, 10.0), 1);
2424                assert_eq!(did_receive_pointer_down.get(), received, "{behavior:?}");
2425            }
2426        });
2427    }
2428
2429    #[test]
2430    fn dismiss_direction_none_does_not_dismiss() {
2431        test_widgets(|tester| {
2432            let results = Results::new();
2433            tester.pump_widget(build_test(
2434                &results,
2435                BuildTest {
2436                    dismiss_direction: DismissDirection::None,
2437                    scroll_physics: Some(Rc::new(NeverScrollableScrollPhysics::new())),
2438                    ..BuildTest::default()
2439                },
2440            ));
2441            assert!(results.dismissed_items().is_empty());
2442
2443            for direction in [Left, Right, AxisUp, AxisDown] {
2444                dismiss_item(tester, 0, direction, dismiss_element);
2445            }
2446            expect(tester, &find::text("0"), finds_one_widget());
2447        });
2448    }
2449
2450    #[test]
2451    fn dismiss_direction_none_does_not_prevent_scrolling() {
2452        test_widgets(|tester| {
2453            let results = Results::new();
2454            let controller = tester.update(ScrollController::default);
2455            tester.pump_widget(build_test(
2456                &results,
2457                BuildTest {
2458                    controller: Some(controller.clone()),
2459                    dismiss_direction: DismissDirection::None,
2460                    ..BuildTest::default()
2461                },
2462            ));
2463            assert!(results.dismissed_items().is_empty());
2464            assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
2465
2466            dismiss_item(tester, 0, Left, dismiss_element);
2467            assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
2468            dismiss_item(tester, 0, Right, dismiss_element);
2469            assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
2470            dismiss_item(tester, 0, AxisDown, dismiss_element);
2471            assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
2472            dismiss_item(tester, 0, AxisUp, dismiss_element);
2473            // Within f32: pointer positions reach the list through valo's f32 matrices
2474            // (waft-gestures' `push_transform` entry).
2475            assert!((controller.offset(&tester.cell.borrow()) - 100.0).abs() < 1e-4);
2476        });
2477    }
2478
2479    #[test]
2480    fn on_update_reports_the_progress_and_the_threshold() {
2481        test_widgets(|tester| {
2482            let results = Results::new();
2483            tester.pump_widget(build_test(
2484                &results,
2485                BuildTest {
2486                    scroll_direction: Axis::Horizontal,
2487                    ..BuildTest::default()
2488                },
2489            ));
2490            assert!(results.dismissed_items().is_empty());
2491
2492            // Unsuccessful dismiss, fractional progress reported
2493            drag_item(tester, 0, Right, 20.0);
2494            assert_eq!(results.reported_dismiss_update_progress.get(), 0.2);
2495
2496            // Successful dismiss therefore threshold has been reached
2497            dismiss_item(tester, 0, Left, fling_element);
2498            expect(tester, &find::text("0"), finds_nothing());
2499            assert_eq!(results.dismissed_items(), [0]);
2500            assert_eq!(
2501                results.reported_dismiss_update_reached_direction.get(),
2502                Some(DismissDirection::EndToStart)
2503            );
2504            assert!(results.reported_dismiss_update_reached.get());
2505            assert!(results.reported_dismiss_update_previous_reached.get());
2506            assert_eq!(results.reported_dismiss_update_progress.get(), 1.0);
2507
2508            // Unsuccessful dismiss, threshold has not been reached
2509            check_fling_item_after_movement(tester, 1, Right, rollback_element);
2510            expect(tester, &find::text("1"), finds_one_widget());
2511            assert_eq!(results.dismissed_items(), [0]);
2512            assert_eq!(
2513                results.reported_dismiss_update_reached_direction.get(),
2514                Some(DismissDirection::StartToEnd)
2515            );
2516            assert!(!results.reported_dismiss_update_reached.get());
2517            assert!(!results.reported_dismiss_update_previous_reached.get());
2518            assert_eq!(results.reported_dismiss_update_progress.get(), 0.0);
2519
2520            // Another successful dismiss from another direction
2521            dismiss_item(tester, 1, Right, fling_element);
2522            expect(tester, &find::text("1"), finds_nothing());
2523            assert_eq!(results.dismissed_items(), [0, 1]);
2524            assert_eq!(
2525                results.reported_dismiss_update_reached_direction.get(),
2526                Some(DismissDirection::StartToEnd)
2527            );
2528            assert!(results.reported_dismiss_update_reached.get());
2529            assert!(results.reported_dismiss_update_previous_reached.get());
2530            assert_eq!(results.reported_dismiss_update_progress.get(), 1.0);
2531
2532            tester.pump_widget(build_test(
2533                &results,
2534                BuildTest {
2535                    scroll_direction: Axis::Horizontal,
2536                    confirm_dismiss: Some(Rc::new(|_app, _direction| Task::ready(Some(false)))),
2537                    ..BuildTest::default()
2538                },
2539            ));
2540
2541            // Threshold has been reached but dismiss was not confirmed
2542            dismiss_item(tester, 2, Right, fling_element);
2543            expect(tester, &find::text("2"), finds_one_widget());
2544            assert_eq!(results.dismissed_items(), [0, 1]);
2545            assert_eq!(
2546                results.reported_dismiss_update_reached_direction.get(),
2547                Some(DismissDirection::StartToEnd)
2548            );
2549            assert!(!results.reported_dismiss_update_reached.get());
2550            assert!(!results.reported_dismiss_update_previous_reached.get());
2551            assert_eq!(results.reported_dismiss_update_progress.get(), 0.0);
2552        });
2553    }
2554
2555    #[test]
2556    fn changing_the_direction_keeps_the_child_state() {
2557        test_widgets(|tester| {
2558            let build_frame = |direction: DismissDirection| {
2559                Directionality::new(
2560                    TextDirection::Ltr,
2561                    Dismissible::new(
2562                        ValueKey::new("Dismissible").into(),
2563                        SizedBox::new()
2564                            .width(100.0)
2565                            .height(100.0)
2566                            .child(Text::new("I Love Flutter!")),
2567                    )
2568                    .drag_start_behavior(DragStartBehavior::Down)
2569                    .direction(direction)
2570                    .resize_duration(None),
2571                )
2572                .into_widget()
2573            };
2574
2575            tester.pump_widget(build_frame(DismissDirection::Horizontal));
2576            let text_render_object_begin = tester.render_object(find::text("I Love Flutter!"));
2577
2578            tester.pump_widget(build_frame(DismissDirection::None));
2579            let text_render_object_end = tester.render_object(find::text("I Love Flutter!"));
2580
2581            assert_eq!(text_render_object_begin, text_render_object_end);
2582        });
2583    }
2584}