Skip to main content

waft_widgets/widgets/
reorderable_list.rs

1//! Flutter counterpart: `widgets/reorderable_list.dart`.
2//!
3//! A [`SliverReorderableList`] keeps the state of every item it has built under its index;
4//! an item drag replaces the item by a gap of its extent, shows the item in the [`Overlay`]
5//! as a proxy that follows the pointer, and slides the items between the gap and the item's
6//! old place by the gap's extent. The map is the order Dart's `LinkedHashMap` keeps, which
7//! the search for the insertion index depends on.
8
9use std::any::{Any, TypeId};
10use std::fmt::{self, Debug};
11use std::hash::{Hash, Hasher};
12use std::rc::Rc;
13use std::time::Duration;
14
15use indexmap::IndexMap;
16use waft_animation::{
17    Animation, AnimationBehavior, AnimationController, AnimationRef, AnimationStatusListener,
18    Curves,
19};
20use waft_embedder::{Clip, Offset, Rect, Size, TextDirection};
21use waft_foundation::{
22    App, Handle, HandleId, Key, Listenable, Listener, OptionRetained, Ref, VoidCallback,
23};
24use waft_gestures::{
25    DelayedMultiDragGestureRecognizer, Drag, DragEndDetails, DragObject, DragStartBehavior,
26    DragUpdateDetails, GestureMultiDragStartCallback, ImmediateMultiDragGestureRecognizer,
27    MultiDragRecognizerRef, PointerDownEvent,
28};
29use waft_painting::{
30    AlignmentGeometry, Axis, EdgeInsetsGeometry, axis_direction_is_reversed, axis_direction_to_axis,
31};
32use waft_rendering::{BoxConstraints, CustomSemanticsAction, ItemExtentBuilder, ScrollCacheExtent};
33use waft_scheduler::{Ticker, TickerCallback, TickerProvider, TickerProviderObject};
34
35use crate::framework::{
36    BuildContext, GlobalKey, IntoWidget, KeyRef, State, StateData, StatefulWidget, StatelessWidget,
37    WidgetRef,
38};
39use crate::widgets::basic::{
40    Directionality, IndexedWidgetBuilder, Listener as PointerListener, OverflowBox, Positioned,
41    Semantics, SizedBox, SliverPadding, Transform,
42};
43use crate::widgets::debug::debug_check_has_overlay;
44use crate::widgets::drag_boundary::{DragBoundary, DragBoundaryDelegate};
45use crate::widgets::inherited_theme::{CapturedThemes, InheritedTheme};
46use crate::widgets::localizations::WidgetsLocalizations;
47use crate::widgets::media_query::MediaQuery;
48use crate::widgets::overlay::{Overlay, OverlayEntry};
49use crate::widgets::scroll_context::ScrollContext;
50use crate::widgets::scroll_controller::ScrollControllerRef;
51use crate::widgets::scroll_delegate::{ChildIndexGetter, SliverChildBuilderDelegate};
52use crate::widgets::scroll_physics::ScrollPhysicsRef;
53use crate::widgets::scroll_view::{CustomScrollView, ScrollViewKeyboardDismissBehavior};
54use crate::widgets::scrollable::{Scrollable, ScrollableState};
55use crate::widgets::scrollable_helpers::EdgeDraggingAutoScroller;
56use crate::widgets::sliver::{SliverFixedExtentList, SliverList, SliverVariedExtentList};
57use crate::widgets::sliver_prototype_extent_list::SliverPrototypeExtentList;
58use crate::widgets::ticker_provider::{TickerProviderStateMixin, TickerProviderStateMixinData};
59use crate::widgets::transitions::AnimatedBuilder;
60
61/// A callback used by [`ReorderableList`] to report that a list item has moved to a new
62/// position in the list.
63///
64/// Implementations should remove the corresponding list item at `old_index` and reinsert it
65/// at `new_index`.
66///
67/// See also:
68///
69///  * [`ReorderableList`], a widget list that allows the user to reorder its items.
70///  * [`SliverReorderableList`], a sliver list that allows the user to reorder its items.
71///  * `ReorderableListView`, a Material Design list that allows the user to reorder its items.
72pub type ReorderCallback = Rc<dyn Fn(&mut App, i32, i32)>;
73
74/// Signature for the builder callback used to decorate the dragging item in
75/// [`ReorderableList`] and [`SliverReorderableList`].
76///
77/// The `child` will be the item that is being dragged, and `index` is the position of the
78/// item in the list.
79///
80/// The `animation` will be driven forward from 0.0 to 1.0 while the item is being picked up
81/// during a drag operation, and reversed from 1.0 to 0.0 when the item is dropped. This can be
82/// used to animate properties of the proxy like an elevation or border.
83///
84/// The returned value will typically be the `child` wrapped in other widgets.
85pub type ReorderItemProxyDecorator =
86    Rc<dyn Fn(&mut App, WidgetRef, i32, AnimationRef<f64>) -> WidgetRef>;
87
88/// Used to provide drag boundaries during drag-and-drop reordering.
89///
90/// See also:
91/// * [`DragBoundary`], a widget that provides drag boundaries.
92pub type ReorderDragBoundaryProvider =
93    Rc<dyn Fn(&mut App, BuildContext) -> Option<Box<dyn DragBoundaryDelegate<Rect>>>>;
94
95/// Dart's `void Function(int index)` of `onReorderStart` and `onReorderEnd`.
96pub type ReorderIndexCallback = Rc<dyn Fn(&mut App, i32)>;
97
98/// A scrolling container that allows the user to interactively reorder the list items.
99///
100/// This widget is similar to one created by `ListView.builder`, and uses an
101/// [`IndexedWidgetBuilder`] to create each item.
102///
103/// It is up to the application to wrap each child (or an internal part of the child such as a
104/// drag handle) with a drag listener that will recognize the start of an item drag and then
105/// start the reorder by calling [`ReorderableListState::start_item_drag_reorder`]. This is
106/// most easily achieved by wrapping each child in a [`ReorderableDragStartListener`] or a
107/// [`ReorderableDelayedDragStartListener`]. These will take care of recognizing the start of a
108/// drag gesture and call the list state's
109/// [`ReorderableListState::start_item_drag_reorder`] method.
110///
111/// This widget's [`ReorderableListState`] can be used to manually start an item reorder, or
112/// cancel a current drag. To refer to the [`ReorderableListState`] either provide a
113/// [`GlobalKey`] or use the static [`ReorderableList::of`] method from an item's build method.
114///
115/// See also:
116///
117///  * [`SliverReorderableList`], a sliver list that allows the user to reorder its items.
118///  * `ReorderableListView`, a Material Design list that allows the user to reorder its items.
119pub struct ReorderableList {
120    pub key: Option<KeyRef>,
121
122    /// Called, as needed, to build list item widgets.
123    ///
124    /// List items are only built when they're scrolled into view.
125    ///
126    /// The [`IndexedWidgetBuilder`] index parameter indicates the item's position in the list.
127    /// The value of the index parameter will be between zero and one less than
128    /// [`item_count`](Self::item_count). All items in the list must have a unique [`Key`],
129    /// and should have some kind of listener to start the drag (usually a
130    /// [`ReorderableDragStartListener`] or [`ReorderableDelayedDragStartListener`]).
131    pub item_builder: IndexedWidgetBuilder,
132
133    /// The number of items in the list.
134    ///
135    /// It must be a non-negative integer. When zero, nothing is displayed and the widget
136    /// occupies no space.
137    pub item_count: i32,
138
139    /// A callback used by the list to report that a list item has been dragged to a new
140    /// location in the list and the application should update the order of the items.
141    ///
142    /// If `old_index` is before `new_index`, removing the item at `old_index` from the list
143    /// will reduce the list's length by one. Implementations will need to account for this
144    /// when inserting before `new_index`.
145    ///
146    /// Deprecated in favor of [`on_reorder_item`](Self::on_reorder_item), which simplifies
147    /// the reordering logic by automatically handling index adjustments. To migrate, remove the
148    /// manual adjustment of `new_index` when items are moved downward in the list.
149    pub on_reorder: Option<ReorderCallback>,
150
151    /// A callback used by the list to report that a list item has been dragged to a new
152    /// location in the list and the application should update the order of the items.
153    pub on_reorder_item: Option<ReorderCallback>,
154
155    /// A callback that is called when an item drag has started.
156    ///
157    /// The index parameter of the callback is the index of the selected item.
158    ///
159    /// See also:
160    ///
161    ///   * [`on_reorder_end`](Self::on_reorder_end), which is a called when the dragged item
162    ///     is dropped.
163    ///   * [`on_reorder_item`](Self::on_reorder_item), which reports that a list item has been
164    ///     dragged to a new location.
165    pub on_reorder_start: Option<ReorderIndexCallback>,
166
167    /// A callback that is called when the dragged item is dropped.
168    ///
169    /// The index parameter of the callback is the index where the item is dropped. Unlike
170    /// [`on_reorder_item`](Self::on_reorder_item), this is called even when the list item is
171    /// dropped in the same location.
172    ///
173    /// See also:
174    ///
175    ///   * [`on_reorder_start`](Self::on_reorder_start), which is a called when an item drag
176    ///     has started.
177    ///   * [`on_reorder_item`](Self::on_reorder_item), which reports that a list item has been
178    ///     dragged to a new location.
179    pub on_reorder_end: Option<ReorderIndexCallback>,
180
181    /// A callback that allows the app to add an animated decoration around an item when it is
182    /// being dragged.
183    pub proxy_decorator: Option<ReorderItemProxyDecorator>,
184
185    /// The amount of space by which to inset the list contents.
186    ///
187    /// It defaults to `EdgeInsets.all(0)`.
188    pub padding: Option<EdgeInsetsGeometry>,
189
190    /// The [`Axis`] along which the scroll view's offset increases.
191    pub scroll_direction: Axis,
192
193    /// Whether the scroll view scrolls in the reading direction.
194    pub reverse: bool,
195
196    /// An object that can be used to control the position to which this scroll view is
197    /// scrolled.
198    pub controller: Option<ScrollControllerRef>,
199
200    /// Whether this is the primary scroll view associated with the parent
201    /// `PrimaryScrollController`.
202    pub primary: Option<bool>,
203
204    /// How the scroll view should respond to user input.
205    pub physics: Option<ScrollPhysicsRef>,
206
207    /// Whether the extent of the scroll view in the scroll direction should be determined by
208    /// the contents being viewed.
209    pub shrink_wrap: bool,
210
211    /// The relative position of the zero scroll offset.
212    pub anchor: f64,
213
214    /// The viewport has an area before and after the visible area to cache items that are
215    /// about to become visible when the user scrolls.
216    ///
217    /// Deprecated: use [`scroll_cache_extent`](Self::scroll_cache_extent) instead.
218    pub cache_extent: Option<f64>,
219
220    /// The amount of additional content to display and lay out around the viewport.
221    pub scroll_cache_extent: Option<ScrollCacheExtent>,
222
223    /// Determines the way that drag start behavior is handled.
224    pub drag_start_behavior: DragStartBehavior,
225
226    /// The [`ScrollViewKeyboardDismissBehavior`] defines how this scroll view will dismiss
227    /// the keyboard automatically.
228    ///
229    /// If it is `None` then it will fallback to the inherited
230    /// `ScrollBehavior::get_keyboard_dismiss_behavior`.
231    pub keyboard_dismiss_behavior: Option<ScrollViewKeyboardDismissBehavior>,
232
233    /// Restoration ID to save and restore the scroll offset of the scrollable.
234    pub restoration_id: Option<String>,
235
236    /// The content will be clipped (or not) according to this option.
237    ///
238    /// Defaults to [`Clip::HardEdge`].
239    pub clip_behavior: Clip,
240
241    /// If non-`None`, forces the children to have the given extent in the scroll direction.
242    pub item_extent: Option<f64>,
243
244    /// Called to get the item extent of the children in the scroll direction.
245    pub item_extent_builder: Option<ItemExtentBuilder>,
246
247    /// If non-`None`, forces the children to have the same extent as the given widget in the
248    /// scroll direction.
249    pub prototype_item: Option<WidgetRef>,
250
251    /// The velocity scalar per pixel over scroll of the auto scroller.
252    ///
253    /// Defaults to 50 if not set or set to `None`.
254    pub auto_scroller_velocity_scalar: Option<f64>,
255
256    /// A callback used to provide drag boundaries during drag-and-drop reordering.
257    ///
258    /// If `None`, the delegate returned by [`DragBoundary::for_rect_maybe_of`] will be used.
259    /// Defaults to `None`.
260    pub drag_boundary_provider: Option<ReorderDragBoundaryProvider>,
261}
262
263impl ReorderableList {
264    /// Creates a scrolling container that allows the user to interactively reorder the list
265    /// items.
266    ///
267    /// The `item_count` must be greater than or equal to zero.
268    pub fn new(
269        item_builder: impl Fn(&mut App, BuildContext, i32) -> WidgetRef + 'static,
270        item_count: i32,
271    ) -> ReorderableList {
272        debug_assert!(item_count >= 0);
273        ReorderableList {
274            key: None,
275            item_builder: Rc::new(item_builder),
276            item_count,
277            on_reorder: None,
278            on_reorder_item: None,
279            on_reorder_start: None,
280            on_reorder_end: None,
281            proxy_decorator: None,
282            padding: None,
283            scroll_direction: Axis::Vertical,
284            reverse: false,
285            controller: None,
286            primary: None,
287            physics: None,
288            shrink_wrap: false,
289            anchor: 0.0,
290            cache_extent: None,
291            scroll_cache_extent: None,
292            drag_start_behavior: DragStartBehavior::Start,
293            keyboard_dismiss_behavior: None,
294            restoration_id: None,
295            clip_behavior: Clip::HardEdge,
296            item_extent: None,
297            item_extent_builder: None,
298            prototype_item: None,
299            auto_scroller_velocity_scalar: None,
300            drag_boundary_provider: None,
301        }
302    }
303
304    /// Dart `ReorderableList(key:)`.
305    pub fn key(mut self, key: KeyRef) -> ReorderableList {
306        self.key = Some(key);
307        self
308    }
309
310    /// Dart `ReorderableList(onReorder:)`.
311    #[deprecated(
312        note = "Use the on_reorder_item callback instead. The on_reorder_item callback adjusts \
313                the new_index parameter for a removed item at the old_index."
314    )]
315    pub fn on_reorder(
316        mut self,
317        on_reorder: impl Fn(&mut App, i32, i32) + 'static,
318    ) -> ReorderableList {
319        self.on_reorder = Some(Rc::new(on_reorder));
320        self
321    }
322
323    /// Dart `ReorderableList(onReorderItem:)`.
324    pub fn on_reorder_item(
325        mut self,
326        on_reorder_item: impl Fn(&mut App, i32, i32) + 'static,
327    ) -> ReorderableList {
328        self.on_reorder_item = Some(Rc::new(on_reorder_item));
329        self
330    }
331
332    /// Dart `ReorderableList(onReorderStart:)`.
333    pub fn on_reorder_start(
334        mut self,
335        on_reorder_start: impl Fn(&mut App, i32) + 'static,
336    ) -> ReorderableList {
337        self.on_reorder_start = Some(Rc::new(on_reorder_start));
338        self
339    }
340
341    /// Dart `ReorderableList(onReorderEnd:)`.
342    pub fn on_reorder_end(
343        mut self,
344        on_reorder_end: impl Fn(&mut App, i32) + 'static,
345    ) -> ReorderableList {
346        self.on_reorder_end = Some(Rc::new(on_reorder_end));
347        self
348    }
349
350    /// Dart `ReorderableList(itemExtent:)`.
351    pub fn item_extent(mut self, item_extent: f64) -> ReorderableList {
352        self.item_extent = Some(item_extent);
353        self
354    }
355
356    /// Dart `ReorderableList(itemExtentBuilder:)`.
357    pub fn item_extent_builder(
358        mut self,
359        item_extent_builder: ItemExtentBuilder,
360    ) -> ReorderableList {
361        self.item_extent_builder = Some(item_extent_builder);
362        self
363    }
364
365    /// Dart `ReorderableList(prototypeItem:)`.
366    #[cfg_attr(debug_assertions, track_caller)]
367    pub fn prototype_item<K>(mut self, prototype_item: impl IntoWidget<K>) -> ReorderableList {
368        self.prototype_item = Some(prototype_item.into_widget());
369        self
370    }
371
372    /// Dart `ReorderableList(proxyDecorator:)`.
373    pub fn proxy_decorator(
374        mut self,
375        proxy_decorator: impl Fn(&mut App, WidgetRef, i32, AnimationRef<f64>) -> WidgetRef + 'static,
376    ) -> ReorderableList {
377        self.proxy_decorator = Some(Rc::new(proxy_decorator));
378        self
379    }
380
381    /// Dart `ReorderableList(padding:)`.
382    pub fn padding(mut self, padding: impl Into<EdgeInsetsGeometry>) -> ReorderableList {
383        let padding = padding.into();
384        self.padding = Some(padding);
385        self
386    }
387
388    /// Dart `ReorderableList(scrollDirection:)`.
389    pub fn scroll_direction(mut self, scroll_direction: Axis) -> ReorderableList {
390        self.scroll_direction = scroll_direction;
391        self
392    }
393
394    /// Dart `ReorderableList(reverse:)`.
395    pub fn reverse(mut self, reverse: bool) -> ReorderableList {
396        self.reverse = reverse;
397        self
398    }
399
400    /// Dart `ReorderableList(controller:)`.
401    pub fn controller(mut self, controller: ScrollControllerRef) -> ReorderableList {
402        self.controller = Some(controller);
403        self
404    }
405
406    /// Dart `ReorderableList(primary:)`.
407    pub fn primary(mut self, primary: bool) -> ReorderableList {
408        self.primary = Some(primary);
409        self
410    }
411
412    /// Dart `ReorderableList(physics:)`.
413    pub fn physics(mut self, physics: ScrollPhysicsRef) -> ReorderableList {
414        self.physics = Some(physics);
415        self
416    }
417
418    /// Dart `ReorderableList(shrinkWrap:)`.
419    pub fn shrink_wrap(mut self, shrink_wrap: bool) -> ReorderableList {
420        self.shrink_wrap = shrink_wrap;
421        self
422    }
423
424    /// Dart `ReorderableList(anchor:)`.
425    pub fn anchor(mut self, anchor: f64) -> ReorderableList {
426        self.anchor = anchor;
427        self
428    }
429
430    /// Dart `ReorderableList(cacheExtent:)`.
431    #[deprecated(note = "Use scroll_cache_extent instead.")]
432    pub fn cache_extent(mut self, cache_extent: f64) -> ReorderableList {
433        self.cache_extent = Some(cache_extent);
434        self
435    }
436
437    /// Dart `ReorderableList(scrollCacheExtent:)`.
438    pub fn scroll_cache_extent(
439        mut self,
440        scroll_cache_extent: ScrollCacheExtent,
441    ) -> ReorderableList {
442        self.scroll_cache_extent = Some(scroll_cache_extent);
443        self
444    }
445
446    /// Dart `ReorderableList(dragStartBehavior:)`.
447    pub fn drag_start_behavior(
448        mut self,
449        drag_start_behavior: DragStartBehavior,
450    ) -> ReorderableList {
451        self.drag_start_behavior = drag_start_behavior;
452        self
453    }
454
455    /// Dart `ReorderableList(keyboardDismissBehavior:)`.
456    pub fn keyboard_dismiss_behavior(
457        mut self,
458        keyboard_dismiss_behavior: ScrollViewKeyboardDismissBehavior,
459    ) -> ReorderableList {
460        self.keyboard_dismiss_behavior = Some(keyboard_dismiss_behavior);
461        self
462    }
463
464    /// Dart `ReorderableList(restorationId:)`.
465    pub fn restoration_id(mut self, restoration_id: impl Into<String>) -> ReorderableList {
466        self.restoration_id = Some(restoration_id.into());
467        self
468    }
469
470    /// Dart `ReorderableList(clipBehavior:)`.
471    pub fn clip_behavior(mut self, clip_behavior: Clip) -> ReorderableList {
472        self.clip_behavior = clip_behavior;
473        self
474    }
475
476    /// Dart `ReorderableList(autoScrollerVelocityScalar:)`.
477    pub fn auto_scroller_velocity_scalar(mut self, value: f64) -> ReorderableList {
478        self.auto_scroller_velocity_scalar = Some(value);
479        self
480    }
481
482    /// Dart `ReorderableList(dragBoundaryProvider:)`.
483    pub fn drag_boundary_provider(
484        mut self,
485        drag_boundary_provider: impl Fn(
486            &mut App,
487            BuildContext,
488        ) -> Option<Box<dyn DragBoundaryDelegate<Rect>>>
489        + 'static,
490    ) -> ReorderableList {
491        self.drag_boundary_provider = Some(Rc::new(drag_boundary_provider));
492        self
493    }
494
495    /// The state from the closest instance of this class that encloses the given context.
496    ///
497    /// This method is typically used by [`ReorderableList`] item widgets that insert or remove
498    /// items in response to user input.
499    ///
500    /// If no [`ReorderableList`] surrounds the given context, then this function will panic.
501    ///
502    /// This method can be expensive (it walks the element tree).
503    ///
504    /// See also:
505    ///
506    ///  * [`maybe_of`](Self::maybe_of), a similar function that will return `None` if no
507    ///    [`ReorderableList`] ancestor is found.
508    pub fn of(app: &App, context: BuildContext) -> Handle<ReorderableListState> {
509        let result = context.find_ancestor_state_of_type::<ReorderableListState>(app);
510        result.unwrap_or_else(|| {
511            panic!(
512                "ReorderableList.of() called with a context that does not contain a \
513                 ReorderableList.\nNo ReorderableList ancestor could be found starting from the \
514                 context that was passed to ReorderableList.of().\nThis can happen when the \
515                 context provided is from the same StatefulWidget that built the \
516                 ReorderableList. Please see the ReorderableList documentation for examples of \
517                 how to refer to an ReorderableListState object:\n  \
518                 https://api.flutter.dev/flutter/widgets/ReorderableListState-class.html"
519            )
520        })
521    }
522
523    /// The state from the closest instance of this class that encloses the given context.
524    ///
525    /// This method is typically used by [`ReorderableList`] item widgets that insert or remove
526    /// items in response to user input.
527    ///
528    /// If no [`ReorderableList`] surrounds the context given, then this function will return
529    /// `None`.
530    ///
531    /// This method can be expensive (it walks the element tree).
532    ///
533    /// See also:
534    ///
535    ///  * [`of`](Self::of), a similar function that will panic if no [`ReorderableList`]
536    ///    ancestor is found.
537    pub fn maybe_of(app: &App, context: BuildContext) -> Option<Handle<ReorderableListState>> {
538        context.find_ancestor_state_of_type::<ReorderableListState>(app)
539    }
540}
541
542/// Dart's three constructor asserts that relate two or more arguments, shared by
543/// [`ReorderableList`] and [`SliverReorderableList`].
544fn debug_check_reorderable_arguments(
545    item_extent: Option<f64>,
546    prototype_item: Option<&WidgetRef>,
547    item_extent_builder: Option<&ItemExtentBuilder>,
548    on_reorder: Option<&ReorderCallback>,
549    on_reorder_item: Option<&ReorderCallback>,
550) {
551    debug_assert!(
552        (item_extent.is_none() && prototype_item.is_none())
553            || (item_extent.is_none() && item_extent_builder.is_none())
554            || (prototype_item.is_none() && item_extent_builder.is_none()),
555        "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
556    );
557    debug_assert!(
558        (on_reorder_item.is_some() && on_reorder.is_none())
559            || (on_reorder_item.is_none() && on_reorder.is_some()),
560        "The onReorder callback is obsolete and is replaced by onReorderItem. Remove the \
561         onReorder callback when both callbacks are provided."
562    );
563}
564
565impl Debug for ReorderableList {
566    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
567        f.debug_struct("ReorderableList")
568            .field("key", &self.key)
569            .field("item_count", &self.item_count)
570            .field("scroll_direction", &self.scroll_direction)
571            .field("reverse", &self.reverse)
572            .finish_non_exhaustive()
573    }
574}
575
576impl StatefulWidget for ReorderableList {
577    type State = ReorderableListState;
578
579    fn key(&self) -> Option<&KeyRef> {
580        self.key.as_ref()
581    }
582
583    fn debug_check_constructor(&self) {
584        debug_check_reorderable_arguments(
585            self.item_extent,
586            self.prototype_item.as_ref(),
587            self.item_extent_builder.as_ref(),
588            self.on_reorder.as_ref(),
589            self.on_reorder_item.as_ref(),
590        );
591    }
592
593    fn create_state(&self) -> ReorderableListState {
594        ReorderableListState {
595            state: StateData::new(),
596            sliver_reorderable_list_key: GlobalKey::new(),
597        }
598    }
599}
600
601/// The state for a list that allows the user to interactively reorder the list items.
602///
603/// An app that needs to start a new item drag or cancel an existing one can refer to the
604/// [`ReorderableList`]'s state with a global key, and call
605/// `list_key.current_state::<ReorderableListState>(app).unwrap().cancel_reorder(app)`.
606pub struct ReorderableListState {
607    state: StateData<ReorderableList>,
608    sliver_reorderable_list_key: GlobalKey,
609}
610
611impl ReorderableListState {
612    fn effective_scroll_cache_extent(self: Handle<Self>, app: &App) -> Option<ScrollCacheExtent> {
613        let widget = self.widget(app);
614        if widget.scroll_cache_extent.is_some() {
615            return widget.scroll_cache_extent;
616        }
617
618        if let Some(cache_extent) = widget.cache_extent {
619            return Some(ScrollCacheExtent::Pixels(cache_extent));
620        }
621        None
622    }
623
624    /// Initiate the dragging of the item at `index` that was started with the pointer down
625    /// `event`.
626    ///
627    /// The given `recognizer` will be used to recognize and start the drag item tracking and
628    /// lead to either an item reorder, or a canceled drag. The list will take ownership of the
629    /// returned recognizer and will dispose it when it is no longer needed.
630    ///
631    /// Most applications will not use this directly, but will wrap the item (or part of the
632    /// item, like a drag handle) in either a [`ReorderableDragStartListener`] or
633    /// [`ReorderableDelayedDragStartListener`] which call this for the application.
634    pub fn start_item_drag_reorder(
635        self: Handle<Self>,
636        app: &mut App,
637        index: i32,
638        event: PointerDownEvent,
639        recognizer: MultiDragRecognizerRef,
640    ) {
641        app.get(self)
642            .sliver_reorderable_list_key
643            .current_state::<SliverReorderableListState>(app)
644            .expect("the SliverReorderableList is mounted")
645            .start_item_drag_reorder(app, index, event, recognizer);
646    }
647
648    /// Cancel any item drag in progress.
649    ///
650    /// This should be called before any major changes to the item list occur so that any item
651    /// drags will not get confused by changes to the underlying list.
652    ///
653    /// If no drag is active, this will do nothing.
654    pub fn cancel_reorder(self: Handle<Self>, app: &mut App) {
655        app.get(self)
656            .sliver_reorderable_list_key
657            .current_state::<SliverReorderableListState>(app)
658            .expect("the SliverReorderableList is mounted")
659            .cancel_reorder(app);
660    }
661}
662
663impl State for ReorderableListState {
664    type Widget = ReorderableList;
665    crate::state_accessors!();
666
667    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
668        let scroll_cache_extent = self.effective_scroll_cache_extent(app);
669        let widget = self.widget(app);
670        let mut sliver =
671            SliverReorderableList::from_builder(widget.item_builder.clone(), widget.item_count)
672                .key(app.get(self).sliver_reorderable_list_key.clone().into());
673        sliver.item_extent = widget.item_extent;
674        sliver.prototype_item = widget.prototype_item.clone();
675        sliver.item_extent_builder = widget.item_extent_builder.clone();
676        sliver.on_reorder = widget.on_reorder.clone();
677        sliver.on_reorder_item = widget.on_reorder_item.clone();
678        sliver.on_reorder_start = widget.on_reorder_start.clone();
679        sliver.on_reorder_end = widget.on_reorder_end.clone();
680        sliver.proxy_decorator = widget.proxy_decorator.clone();
681        if let Some(auto_scroller_velocity_scalar) = widget.auto_scroller_velocity_scalar {
682            sliver = sliver.auto_scroller_velocity_scalar(auto_scroller_velocity_scalar);
683        }
684        sliver.drag_boundary_provider = widget.drag_boundary_provider.clone();
685
686        let mut scroll_view = CustomScrollView::new()
687            .scroll_direction(widget.scroll_direction)
688            .reverse(widget.reverse);
689        if let Some(controller) = widget.controller.clone() {
690            scroll_view = scroll_view.controller(controller);
691        }
692        if let Some(primary) = widget.primary {
693            scroll_view = scroll_view.primary(primary);
694        }
695        if let Some(physics) = widget.physics.clone() {
696            scroll_view = scroll_view.physics(physics);
697        }
698        scroll_view = scroll_view
699            .shrink_wrap(widget.shrink_wrap)
700            .anchor(widget.anchor);
701        if let Some(scroll_cache_extent) = scroll_cache_extent {
702            scroll_view = scroll_view.scroll_cache_extent(scroll_cache_extent);
703        }
704        scroll_view = scroll_view.drag_start_behavior(widget.drag_start_behavior);
705        if let Some(keyboard_dismiss_behavior) = widget.keyboard_dismiss_behavior {
706            scroll_view = scroll_view.keyboard_dismiss_behavior(keyboard_dismiss_behavior);
707        }
708        if let Some(restoration_id) = widget.restoration_id.clone() {
709            scroll_view = scroll_view.restoration_id(restoration_id);
710        }
711        scroll_view
712            .clip_behavior(widget.clip_behavior)
713            .slivers([
714                SliverPadding::new(widget.padding.unwrap_or(EdgeInsetsGeometry::ZERO))
715                    .sliver(sliver)
716                    .into_widget(),
717            ])
718            .into_widget()
719    }
720}
721
722/// A sliver list that allows the user to interactively reorder the list items.
723///
724/// It is up to the application to wrap each child (or an internal part of the child) with a
725/// drag listener that will recognize the start of an item drag and then start the reorder by
726/// calling [`SliverReorderableListState::start_item_drag_reorder`]. This is most easily
727/// achieved by wrapping each child in a [`ReorderableDragStartListener`] or a
728/// [`ReorderableDelayedDragStartListener`]. These will take care of recognizing the start of a
729/// drag gesture and call the list state's start item drag method.
730///
731/// This widget's [`SliverReorderableListState`] can be used to manually start an item reorder,
732/// or cancel a current drag that's already underway. To refer to the
733/// [`SliverReorderableListState`] either provide a [`GlobalKey`] or use the static
734/// [`SliverReorderableList::of`] method from an item's build method.
735///
736/// See also:
737///
738///  * [`ReorderableList`], a regular widget list that allows the user to reorder its items.
739///  * `ReorderableListView`, a Material Design list that allows the user to reorder its items.
740pub struct SliverReorderableList {
741    pub key: Option<KeyRef>,
742
743    /// Called, as needed, to build list item widgets; see [`ReorderableList::item_builder`].
744    pub item_builder: IndexedWidgetBuilder,
745
746    /// Called to find the new index of a child based on its key in case of reordering.
747    pub find_child_index_callback: Option<ChildIndexGetter>,
748
749    /// The number of items in the list; see [`ReorderableList::item_count`].
750    pub item_count: i32,
751
752    /// See [`ReorderableList::on_reorder`]. Deprecated: use
753    /// [`on_reorder_item`](Self::on_reorder_item).
754    pub on_reorder: Option<ReorderCallback>,
755
756    /// See [`ReorderableList::on_reorder_item`].
757    pub on_reorder_item: Option<ReorderCallback>,
758
759    /// See [`ReorderableList::on_reorder_start`].
760    pub on_reorder_start: Option<ReorderIndexCallback>,
761
762    /// See [`ReorderableList::on_reorder_end`].
763    pub on_reorder_end: Option<ReorderIndexCallback>,
764
765    /// See [`ReorderableList::proxy_decorator`].
766    pub proxy_decorator: Option<ReorderItemProxyDecorator>,
767
768    /// See [`ReorderableList::item_extent`].
769    pub item_extent: Option<f64>,
770
771    /// See [`ReorderableList::item_extent_builder`].
772    pub item_extent_builder: Option<ItemExtentBuilder>,
773
774    /// See [`ReorderableList::prototype_item`].
775    pub prototype_item: Option<WidgetRef>,
776
777    /// The velocity scalar per pixel over scroll of the auto scroller.
778    ///
779    /// Defaults to 50 if not set or set to `None`.
780    pub auto_scroller_velocity_scalar: f64,
781
782    /// See [`ReorderableList::drag_boundary_provider`].
783    pub drag_boundary_provider: Option<ReorderDragBoundaryProvider>,
784}
785
786impl SliverReorderableList {
787    // An eyeballed value for a smooth scrolling experience.
788    const K_DEFAULT_AUTO_SCROLL_VELOCITY_SCALAR: f64 = 50.0;
789
790    /// Creates a sliver list that allows the user to interactively reorder its items.
791    ///
792    /// The `item_count` must be greater than or equal to zero.
793    pub fn new(
794        item_builder: impl Fn(&mut App, BuildContext, i32) -> WidgetRef + 'static,
795        item_count: i32,
796    ) -> SliverReorderableList {
797        SliverReorderableList::from_builder(Rc::new(item_builder), item_count)
798    }
799
800    /// [`new`](Self::new) from a shared builder, which [`ReorderableList`] passes on.
801    pub fn from_builder(
802        item_builder: IndexedWidgetBuilder,
803        item_count: i32,
804    ) -> SliverReorderableList {
805        debug_assert!(item_count >= 0);
806        SliverReorderableList {
807            key: None,
808            item_builder,
809            find_child_index_callback: None,
810            item_count,
811            on_reorder: None,
812            on_reorder_item: None,
813            on_reorder_start: None,
814            on_reorder_end: None,
815            proxy_decorator: None,
816            item_extent: None,
817            item_extent_builder: None,
818            prototype_item: None,
819            auto_scroller_velocity_scalar:
820                SliverReorderableList::K_DEFAULT_AUTO_SCROLL_VELOCITY_SCALAR,
821            drag_boundary_provider: None,
822        }
823    }
824
825    /// Dart `SliverReorderableList(key:)`.
826    pub fn key(mut self, key: KeyRef) -> SliverReorderableList {
827        self.key = Some(key);
828        self
829    }
830
831    /// Dart `SliverReorderableList(findChildIndexCallback:)`.
832    pub fn find_child_index_callback(
833        mut self,
834        find_child_index_callback: impl Fn(&KeyRef) -> Option<i32> + 'static,
835    ) -> SliverReorderableList {
836        self.find_child_index_callback = Some(Rc::new(find_child_index_callback));
837        self
838    }
839
840    /// Dart `SliverReorderableList(onReorder:)`.
841    #[deprecated(
842        note = "Use the on_reorder_item callback instead. The on_reorder_item callback adjusts \
843                the new_index parameter for a removed item at the old_index."
844    )]
845    pub fn on_reorder(
846        mut self,
847        on_reorder: impl Fn(&mut App, i32, i32) + 'static,
848    ) -> SliverReorderableList {
849        self.on_reorder = Some(Rc::new(on_reorder));
850        self
851    }
852
853    /// Dart `SliverReorderableList(onReorderItem:)`.
854    pub fn on_reorder_item(
855        mut self,
856        on_reorder_item: impl Fn(&mut App, i32, i32) + 'static,
857    ) -> SliverReorderableList {
858        self.on_reorder_item = Some(Rc::new(on_reorder_item));
859        self
860    }
861
862    /// Dart `SliverReorderableList(onReorderStart:)`.
863    pub fn on_reorder_start(
864        mut self,
865        on_reorder_start: impl Fn(&mut App, i32) + 'static,
866    ) -> SliverReorderableList {
867        self.on_reorder_start = Some(Rc::new(on_reorder_start));
868        self
869    }
870
871    /// Dart `SliverReorderableList(onReorderEnd:)`.
872    pub fn on_reorder_end(
873        mut self,
874        on_reorder_end: impl Fn(&mut App, i32) + 'static,
875    ) -> SliverReorderableList {
876        self.on_reorder_end = Some(Rc::new(on_reorder_end));
877        self
878    }
879
880    /// Dart `SliverReorderableList(itemExtent:)`.
881    pub fn item_extent(mut self, item_extent: f64) -> SliverReorderableList {
882        self.item_extent = Some(item_extent);
883        self
884    }
885
886    /// Dart `SliverReorderableList(itemExtentBuilder:)`.
887    pub fn item_extent_builder(
888        mut self,
889        item_extent_builder: ItemExtentBuilder,
890    ) -> SliverReorderableList {
891        self.item_extent_builder = Some(item_extent_builder);
892        self
893    }
894
895    /// Dart `SliverReorderableList(prototypeItem:)`.
896    #[cfg_attr(debug_assertions, track_caller)]
897    pub fn prototype_item<K>(
898        mut self,
899        prototype_item: impl IntoWidget<K>,
900    ) -> SliverReorderableList {
901        self.prototype_item = Some(prototype_item.into_widget());
902        self
903    }
904
905    /// Dart `SliverReorderableList(proxyDecorator:)`.
906    pub fn proxy_decorator(
907        mut self,
908        proxy_decorator: impl Fn(&mut App, WidgetRef, i32, AnimationRef<f64>) -> WidgetRef + 'static,
909    ) -> SliverReorderableList {
910        self.proxy_decorator = Some(Rc::new(proxy_decorator));
911        self
912    }
913
914    /// Dart `SliverReorderableList(dragBoundaryProvider:)`.
915    pub fn drag_boundary_provider(
916        mut self,
917        drag_boundary_provider: impl Fn(
918            &mut App,
919            BuildContext,
920        ) -> Option<Box<dyn DragBoundaryDelegate<Rect>>>
921        + 'static,
922    ) -> SliverReorderableList {
923        self.drag_boundary_provider = Some(Rc::new(drag_boundary_provider));
924        self
925    }
926
927    /// Dart `SliverReorderableList(autoScrollerVelocityScalar:)`.
928    pub fn auto_scroller_velocity_scalar(mut self, value: f64) -> SliverReorderableList {
929        self.auto_scroller_velocity_scalar = value;
930        self
931    }
932
933    /// The state from the closest instance of this class that encloses the given context.
934    ///
935    /// This method is typically used by [`SliverReorderableList`] item widgets to start or
936    /// cancel an item drag operation.
937    ///
938    /// If no [`SliverReorderableList`] surrounds the context given, this function will panic.
939    ///
940    /// This method can be expensive (it walks the element tree).
941    ///
942    /// See also:
943    ///
944    ///  * [`maybe_of`](Self::maybe_of), a similar function that will return `None` if no
945    ///    [`SliverReorderableList`] ancestor is found.
946    pub fn of(app: &App, context: BuildContext) -> Handle<SliverReorderableListState> {
947        let result = context.find_ancestor_state_of_type::<SliverReorderableListState>(app);
948        result.unwrap_or_else(|| {
949            panic!(
950                "SliverReorderableList.of() called with a context that does not contain a \
951                 SliverReorderableList.\nNo SliverReorderableList ancestor could be found \
952                 starting from the context that was passed to SliverReorderableList.of().\nThis \
953                 can happen when the context provided is from the same StatefulWidget that built \
954                 the SliverReorderableList. Please see the SliverReorderableList documentation \
955                 for examples of how to refer to an SliverReorderableList object:\n  \
956                 https://api.flutter.dev/flutter/widgets/SliverReorderableListState-class.html"
957            )
958        })
959    }
960
961    /// The state from the closest instance of this class that encloses the given context.
962    ///
963    /// This method is typically used by [`SliverReorderableList`] item widgets that insert or
964    /// remove items in response to user input.
965    ///
966    /// If no [`SliverReorderableList`] surrounds the context given, this function will return
967    /// `None`.
968    ///
969    /// This method can be expensive (it walks the element tree).
970    ///
971    /// See also:
972    ///
973    ///  * [`of`](Self::of), a similar function that will panic if no
974    ///    [`SliverReorderableList`] ancestor is found.
975    pub fn maybe_of(
976        app: &App,
977        context: BuildContext,
978    ) -> Option<Handle<SliverReorderableListState>> {
979        context.find_ancestor_state_of_type::<SliverReorderableListState>(app)
980    }
981}
982
983impl Debug for SliverReorderableList {
984    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
985        f.debug_struct("SliverReorderableList")
986            .field("key", &self.key)
987            .field("item_count", &self.item_count)
988            .field("item_extent", &self.item_extent)
989            .field(
990                "auto_scroller_velocity_scalar",
991                &self.auto_scroller_velocity_scalar,
992            )
993            .finish_non_exhaustive()
994    }
995}
996
997impl StatefulWidget for SliverReorderableList {
998    type State = SliverReorderableListState;
999
1000    fn key(&self) -> Option<&KeyRef> {
1001        self.key.as_ref()
1002    }
1003
1004    fn debug_check_constructor(&self) {
1005        debug_check_reorderable_arguments(
1006            self.item_extent,
1007            self.prototype_item.as_ref(),
1008            self.item_extent_builder.as_ref(),
1009            self.on_reorder.as_ref(),
1010            self.on_reorder_item.as_ref(),
1011        );
1012    }
1013
1014    fn create_state(&self) -> SliverReorderableListState {
1015        SliverReorderableListState {
1016            state: StateData::new(),
1017            ticker_provider: TickerProviderStateMixinData::new(),
1018            items: IndexMap::new(),
1019            overlay_entry: None,
1020            drag_index: None,
1021            drag_info: None,
1022            insert_index: None,
1023            final_drop_position: None,
1024            recognizer: None,
1025            recognizer_pointer: None,
1026            auto_scroller: None,
1027            scrollable: None,
1028        }
1029    }
1030}
1031
1032/// The state for a sliver list that allows the user to interactively reorder the list items.
1033///
1034/// An app that needs to start a new item drag or cancel an existing one can refer to the
1035/// [`SliverReorderableList`]'s state with a global key, and call
1036/// `list_key.current_state::<SliverReorderableListState>(app).unwrap().cancel_reorder(app)`.
1037///
1038/// [`ReorderableDragStartListener`] and [`ReorderableDelayedDragStartListener`] refer to their
1039/// [`SliverReorderableList`] with the static [`SliverReorderableList::of`] method.
1040pub struct SliverReorderableListState {
1041    state: StateData<SliverReorderableList>,
1042    ticker_provider: TickerProviderStateMixinData,
1043
1044    // Map of index -> child state used manage where the dragging item will need to be
1045    // inserted.
1046    items: IndexMap<i32, Handle<ReorderableItemState>>,
1047
1048    overlay_entry: Option<Ref<OverlayEntry>>,
1049    drag_index: Option<i32>,
1050    drag_info: Option<Ref<DragInfo>>,
1051    insert_index: Option<i32>,
1052    final_drop_position: Option<Offset>,
1053    recognizer: Option<MultiDragRecognizerRef>,
1054    recognizer_pointer: Option<i64>,
1055
1056    auto_scroller: Option<Ref<EdgeDraggingAutoScroller>>,
1057
1058    // Dart's `late`: set in `did_change_dependencies`, before anything reads it.
1059    scrollable: Option<Handle<ScrollableState>>,
1060}
1061
1062impl SliverReorderableListState {
1063    fn scrollable(self: Handle<Self>, app: &App) -> Handle<ScrollableState> {
1064        app.get(self)
1065            .scrollable
1066            .expect("set in did_change_dependencies")
1067    }
1068
1069    fn scroll_direction(self: Handle<Self>, app: &App) -> Axis {
1070        axis_direction_to_axis(self.scrollable(app).axis_direction(app))
1071    }
1072
1073    fn reverse(self: Handle<Self>, app: &App) -> bool {
1074        axis_direction_is_reversed(self.scrollable(app).axis_direction(app))
1075    }
1076
1077    fn drag_info(self: Handle<Self>, app: &App) -> Handle<DragInfo> {
1078        app.get(self)
1079            .drag_info
1080            .handle()
1081            .expect("a drag is in progress")
1082    }
1083
1084    fn new_auto_scroller(self: Handle<Self>, app: &mut App) -> Ref<EdgeDraggingAutoScroller> {
1085        let scrollable = self.scrollable(app);
1086        let velocity_scalar = self.widget(app).auto_scroller_velocity_scalar;
1087        EdgeDraggingAutoScroller::new(
1088            app,
1089            scrollable,
1090            Some(Listener::handle_method(
1091                self,
1092                Self::handle_scrollable_auto_scrolled,
1093            )),
1094            velocity_scalar,
1095        )
1096    }
1097
1098    /// Initiate the dragging of the item at `index` that was started with the pointer down
1099    /// `event`.
1100    ///
1101    /// The given `recognizer` will be used to recognize and start the drag item tracking and
1102    /// lead to either an item reorder, or a canceled drag.
1103    ///
1104    /// Most applications will not use this directly, but will wrap the item (or part of the
1105    /// item, like a drag handle) in either a [`ReorderableDragStartListener`] or
1106    /// [`ReorderableDelayedDragStartListener`] which call this method when they detect the
1107    /// gesture that triggers a drag start.
1108    pub fn start_item_drag_reorder(
1109        self: Handle<Self>,
1110        app: &mut App,
1111        index: i32,
1112        event: PointerDownEvent,
1113        recognizer: MultiDragRecognizerRef,
1114    ) {
1115        debug_assert!(0 <= index && index < self.widget(app).item_count);
1116        if app.get(self).drag_info.is_some() {
1117            self.cancel_reorder(app);
1118        } else if app.get(self).recognizer.is_some()
1119            && app.get(self).recognizer_pointer != Some(event.pointer)
1120        {
1121            if let Some(recognizer) = app.get_mut(self).recognizer.take() {
1122                recognizer.dispose(app);
1123            }
1124            app.get_mut(self).recognizer_pointer = None;
1125        }
1126
1127        if app.get(self).items.contains_key(&index) {
1128            app.get_mut(self).drag_index = Some(index);
1129            let on_start: GestureMultiDragStartCallback =
1130                Rc::new(move |app, position| self.drag_start(app, position));
1131            recognizer.set_on_start(app, Some(on_start));
1132            let pointer = event.pointer;
1133            recognizer.add_pointer(app, &event);
1134            let state = app.get_mut(self);
1135            state.recognizer = Some(recognizer);
1136            state.recognizer_pointer = Some(pointer);
1137        } else {
1138            panic!("Attempting to start a drag on a non-visible item");
1139        }
1140        self.set_state(app, |_| {});
1141    }
1142
1143    /// Cancel any item drag in progress.
1144    ///
1145    /// This should be called before any major changes to the item list occur so that any item
1146    /// drags will not get confused by changes to the underlying list.
1147    ///
1148    /// If a drag operation is in progress, this will immediately reset the list to back to its
1149    /// pre-drag state.
1150    ///
1151    /// If no drag is active, this will do nothing.
1152    pub fn cancel_reorder(self: Handle<Self>, app: &mut App) {
1153        self.drag_reset(app);
1154        self.set_state(app, |_| {});
1155    }
1156
1157    fn register_item(self: Handle<Self>, app: &mut App, item: Handle<ReorderableItemState>) {
1158        let item_index = item.index(app);
1159        if let Some(drag_info) = app.get(self).drag_info.handle()
1160            && app.get(self).items.get(&item_index) != Some(&item)
1161        {
1162            let (index, item_extent) = (app.get(drag_info).index, app.get(drag_info).item_extent);
1163            let reverse = self.reverse(app);
1164            item.update_for_gap(app, index, index, item_extent, false, reverse);
1165        }
1166        app.get_mut(self).items.insert(item_index, item);
1167        let drag_info_index = app
1168            .get(self)
1169            .drag_info
1170            .handle()
1171            .map(|drag_info| app.get(drag_info).index);
1172        if Some(item_index) == drag_info_index {
1173            item.set_dragging(app, true);
1174            item.rebuild(app);
1175        }
1176    }
1177
1178    fn unregister_item(
1179        self: Handle<Self>,
1180        app: &mut App,
1181        index: i32,
1182        item: Handle<ReorderableItemState>,
1183    ) {
1184        let current_item = app.get(self).items.get(&index).copied();
1185        if current_item == Some(item) {
1186            app.get_mut(self).items.shift_remove(&index);
1187        }
1188    }
1189
1190    fn drag_start(self: Handle<Self>, app: &mut App, position: Offset) -> Option<Rc<dyn Drag>> {
1191        debug_assert!(app.get(self).drag_info.is_none());
1192        let drag_index = app
1193            .get(self)
1194            .drag_index
1195            .expect("set when the drag was started");
1196        let item = app.get(self).items[&drag_index];
1197        item.set_dragging(app, true);
1198        if let Some(on_reorder_start) = self.widget(app).on_reorder_start.clone() {
1199            on_reorder_start(app, drag_index);
1200        }
1201        item.rebuild(app);
1202
1203        let item_index = item.index(app);
1204        app.get_mut(self).insert_index = Some(item_index);
1205        let scroll_direction = self.scroll_direction(app);
1206        let on_update: DragItemUpdate =
1207            Rc::new(move |app, item, position, delta| self.drag_update(app, item, position, delta));
1208        let on_cancel: DragItemCallback = Rc::new(move |app, item| self.drag_cancel(app, item));
1209        let on_end: DragItemCallback = Rc::new(move |app, item| self.drag_end(app, item));
1210        let on_drop_completed: VoidCallback = Rc::new(move |app| self.drop_completed(app));
1211        let proxy_decorator = self.widget(app).proxy_decorator.clone();
1212        let drag_info = DragInfo::new(
1213            app,
1214            item,
1215            position,
1216            scroll_direction,
1217            Some(on_update),
1218            Some(on_end),
1219            Some(on_cancel),
1220            Some(on_drop_completed),
1221            proxy_decorator,
1222            Rc::new(self),
1223        );
1224        app.get_mut(self).drag_info = Some(drag_info.clone());
1225        drag_info.start_drag(app);
1226
1227        let overlay = Overlay::of(app, self.context(app), false);
1228        debug_assert!(app.get(self).overlay_entry.is_none());
1229        let proxy_source = drag_info.clone();
1230        let overlay_entry = OverlayEntry::new(
1231            app,
1232            Rc::new(move |app, context| proxy_source.create_proxy(app, context)),
1233            false,
1234            false,
1235            false,
1236        );
1237        app.get_mut(self).overlay_entry = Some(overlay_entry.clone());
1238        overlay.insert(app, overlay_entry, None, None);
1239
1240        let insert_index = item_index;
1241        let item_extent = app.get(&drag_info).item_extent;
1242        let reverse = self.reverse(app);
1243        let child_items: Vec<Handle<ReorderableItemState>> =
1244            app.get(self).items.values().copied().collect();
1245        for child_item in child_items {
1246            if child_item == item || !child_item.mounted(app) {
1247                continue;
1248            }
1249            child_item.update_for_gap(app, insert_index, insert_index, item_extent, false, reverse);
1250        }
1251        Some(Rc::new(drag_info))
1252    }
1253
1254    fn drag_update(
1255        self: Handle<Self>,
1256        app: &mut App,
1257        _item: Handle<DragInfo>,
1258        _position: Offset,
1259        _delta: Offset,
1260    ) {
1261        if let Some(overlay_entry) = app.get(self).overlay_entry.handle() {
1262            overlay_entry.mark_needs_build(app);
1263        }
1264        self.drag_update_items(app);
1265        if let Some(auto_scroller) = app.get(self).auto_scroller.handle() {
1266            let drag_target_rect = self.drag_target_rect(app);
1267            auto_scroller.start_auto_scroll_if_necessary(app, drag_target_rect);
1268        }
1269        self.set_state(app, |_| {});
1270    }
1271
1272    fn drag_cancel(self: Handle<Self>, app: &mut App, _item: Handle<DragInfo>) {
1273        self.drag_reset(app);
1274        self.set_state(app, |_| {});
1275    }
1276
1277    fn drag_end(self: Handle<Self>, app: &mut App, item: Handle<DragInfo>) {
1278        let insert_index = app
1279            .get(self)
1280            .insert_index
1281            .expect("set when the drag started");
1282        let (item_index, item_item_extent) = (app.get(item).index, app.get(item).item_extent);
1283        let scroll_direction = self.scroll_direction(app);
1284        let final_drop_position = if insert_index - item_index == 1 {
1285            // When returning to original position from below, insert_index equals
1286            // item.index + 1 because insertion index is calculated with the dragged
1287            // item still present. Use the actual target position for animation.
1288            self.item_offset_at(app, insert_index - 1)
1289        } else if insert_index == item_index {
1290            // No movement - animate to current position
1291            self.item_offset_at(app, insert_index)
1292        } else if self.reverse(app) {
1293            let items_length = app.get(self).items.len() as i32;
1294            if insert_index >= items_length {
1295                // Drop at the starting position of the last element and offset its own extent
1296                self.item_offset_at(app, items_length - 1)
1297                    - extent_offset(item_item_extent, scroll_direction)
1298            } else {
1299                // Drop at the end of the current element occupying the insert position
1300                self.item_offset_at(app, insert_index)
1301                    + extent_offset(self.item_extent_at(app, insert_index), scroll_direction)
1302            }
1303        } else if insert_index == 0 {
1304            // Drop at the starting position of the first element and offset its own extent
1305            self.item_offset_at(app, 0) - extent_offset(item_item_extent, scroll_direction)
1306        } else {
1307            // Drop at the end of the previous element occupying the insert position
1308            let at_index = insert_index - 1;
1309            self.item_offset_at(app, at_index)
1310                + extent_offset(self.item_extent_at(app, at_index), scroll_direction)
1311        };
1312        app.get_mut(self).final_drop_position = Some(final_drop_position);
1313        self.set_state(app, |_| {});
1314        if let Some(on_reorder_end) = self.widget(app).on_reorder_end.clone() {
1315            on_reorder_end(app, insert_index);
1316        }
1317    }
1318
1319    fn drop_completed(self: Handle<Self>, app: &mut App) {
1320        let old_index = app.get(self).drag_index.expect("set when the drag started");
1321        let new_index = app
1322            .get(self)
1323            .insert_index
1324            .expect("set when the drag started");
1325
1326        self.handle_reorder_item(app, old_index, new_index);
1327
1328        self.drag_reset(app);
1329        self.set_state(app, |_| {});
1330    }
1331
1332    fn drag_reset(self: Handle<Self>, app: &mut App) {
1333        let Some(drag_info) = app.get(self).drag_info.handle() else {
1334            return;
1335        };
1336        if let Some(drag_index) = app.get(self).drag_index
1337            && let Some(drag_item) = app.get(self).items.get(&drag_index).copied()
1338        {
1339            app.get_mut(drag_item).dragging = false;
1340            drag_item.rebuild(app);
1341            app.get_mut(self).drag_index = None;
1342        }
1343        drag_info.dispose(app);
1344        app.get_mut(self).drag_info = None;
1345        if let Some(auto_scroller) = app.get(self).auto_scroller.handle() {
1346            auto_scroller.stop_auto_scroll(app);
1347        }
1348        self.reset_item_gap(app);
1349        if let Some(recognizer) = app.get_mut(self).recognizer.take() {
1350            recognizer.dispose(app);
1351        }
1352        if let Some(overlay_entry) = app.get_mut(self).overlay_entry.take() {
1353            overlay_entry.remove(app);
1354            overlay_entry.dispose(app);
1355        }
1356        app.get_mut(self).final_drop_position = None;
1357    }
1358
1359    fn reset_item_gap(self: Handle<Self>, app: &mut App) {
1360        let items: Vec<Handle<ReorderableItemState>> =
1361            app.get(self).items.values().copied().collect();
1362        for item in items {
1363            item.reset_gap(app);
1364        }
1365    }
1366
1367    fn handle_reorder_item(self: Handle<Self>, app: &mut App, old_index: i32, mut new_index: i32) {
1368        if let Some(on_reorder) = self.widget(app).on_reorder.clone()
1369            && old_index != new_index
1370        {
1371            on_reorder(app, old_index, new_index);
1372            return;
1373        }
1374
1375        // Removing an item at the old index shortens the list by one.
1376        if new_index > old_index {
1377            new_index -= 1;
1378        }
1379
1380        if old_index != new_index
1381            && let Some(on_reorder_item) = self.widget(app).on_reorder_item.clone()
1382        {
1383            on_reorder_item(app, old_index, new_index);
1384        }
1385    }
1386
1387    fn handle_scrollable_auto_scrolled(self: Handle<Self>, app: &mut App) {
1388        if app.get(self).drag_info.is_none() {
1389            return;
1390        }
1391        self.drag_update_items(app);
1392        // Continue scrolling if the drag is still in progress.
1393        if let Some(auto_scroller) = app.get(self).auto_scroller.handle() {
1394            let drag_target_rect = self.drag_target_rect(app);
1395            auto_scroller.start_auto_scroll_if_necessary(app, drag_target_rect);
1396        }
1397    }
1398
1399    fn drag_update_items(self: Handle<Self>, app: &mut App) {
1400        let drag_info = self.drag_info(app);
1401        let scroll_direction = self.scroll_direction(app);
1402        let reverse = self.reverse(app);
1403        let drag_index = app.get(self).drag_index.expect("set when the drag started");
1404        let gap_extent = app.get(drag_info).item_extent;
1405        let proxy_item_start = offset_extent(
1406            app.get(drag_info).drag_position - app.get(drag_info).drag_offset,
1407            scroll_direction,
1408        );
1409        let proxy_item_end = proxy_item_start + gap_extent;
1410
1411        // Find the new index for inserting the item being dragged.
1412        let mut new_index = app
1413            .get(self)
1414            .insert_index
1415            .expect("set when the drag started");
1416        let items: Vec<Handle<ReorderableItemState>> =
1417            app.get(self).items.values().copied().collect();
1418        for &item in &items {
1419            let index = item.index(app);
1420            // Skip the dragged item so its original slot does not compete with the other
1421            // items when determining the insertion index.
1422            if index == drag_index || !item.mounted(app) {
1423                continue;
1424            }
1425
1426            let geometry = item.target_geometry(app);
1427            let item_start = if scroll_direction == Axis::Vertical {
1428                geometry.top
1429            } else {
1430                geometry.left
1431            };
1432            let item_extent = if scroll_direction == Axis::Vertical {
1433                geometry.height()
1434            } else {
1435                geometry.width()
1436            };
1437            let item_end = item_start + item_extent;
1438            let item_middle = item_start + item_extent / 2.0;
1439
1440            if reverse {
1441                if item_end >= proxy_item_end && proxy_item_end >= item_middle {
1442                    // The start of the proxy is in the beginning half of the item, so
1443                    // we should swap the item with the gap and we are done looking for
1444                    // the new index.
1445                    new_index = index;
1446                    break;
1447                } else if item_middle >= proxy_item_start && proxy_item_start >= item_start {
1448                    // The end of the proxy is in the ending half of the item, so
1449                    // we should swap the item with the gap and we are done looking for
1450                    // the new index.
1451                    new_index = index + 1;
1452                    break;
1453                } else if item_start > proxy_item_end && new_index < (index + 1) {
1454                    new_index = index + 1;
1455                } else if proxy_item_start > item_end && new_index > index {
1456                    new_index = index;
1457                }
1458            } else if item_start <= proxy_item_start && proxy_item_start <= item_middle {
1459                // The start of the proxy is in the beginning half of the item, so
1460                // we should swap the item with the gap and we are done looking for
1461                // the new index.
1462                new_index = index;
1463                break;
1464            } else if item_middle <= proxy_item_end && proxy_item_end <= item_end {
1465                // The end of the proxy is in the ending half of the item, so
1466                // we should swap the item with the gap and we are done looking for
1467                // the new index.
1468                new_index = index + 1;
1469                break;
1470            } else if item_end < proxy_item_start && new_index < (index + 1) {
1471                new_index = index + 1;
1472            } else if proxy_item_end < item_start && new_index > index {
1473                new_index = index;
1474            }
1475        }
1476
1477        if Some(new_index) != app.get(self).insert_index {
1478            app.get_mut(self).insert_index = Some(new_index);
1479            for &item in &items {
1480                if item.index(app) == drag_index || !item.mounted(app) {
1481                    continue;
1482                }
1483                item.update_for_gap(app, drag_index, new_index, gap_extent, true, reverse);
1484            }
1485        }
1486    }
1487
1488    fn drag_target_rect(self: Handle<Self>, app: &App) -> Rect {
1489        let drag_info = app.get(self.drag_info(app));
1490        let origin = drag_info.drag_position - drag_info.drag_offset;
1491        Rect::from_ltwh(
1492            origin.dx(),
1493            origin.dy(),
1494            drag_info.item_size.width(),
1495            drag_info.item_size.height(),
1496        )
1497    }
1498
1499    fn item_offset_at(self: Handle<Self>, app: &App, index: i32) -> Offset {
1500        app.get(self).items[&index].target_geometry(app).top_left()
1501    }
1502
1503    fn item_extent_at(self: Handle<Self>, app: &App, index: i32) -> f64 {
1504        size_extent(
1505            app.get(self).items[&index].target_geometry(app).size(),
1506            self.scroll_direction(app),
1507        )
1508    }
1509
1510    fn item_builder(
1511        self: Handle<Self>,
1512        app: &mut App,
1513        context: BuildContext,
1514        index: i32,
1515    ) -> WidgetRef {
1516        if let Some(drag_info) = app.get(self).drag_info.handle()
1517            && index >= self.widget(app).item_count
1518        {
1519            let item_extent = app.get(drag_info).item_extent;
1520            return match self.scroll_direction(app) {
1521                Axis::Horizontal => SizedBox::new().width(item_extent).into_widget(),
1522                Axis::Vertical => SizedBox::new().height(item_extent).into_widget(),
1523            };
1524        }
1525        let item_builder = self.widget(app).item_builder.clone();
1526        let child = item_builder(app, context, index);
1527        debug_assert!(child.key().is_some(), "All list items must have a key");
1528        let overlay = Overlay::of(app, context, false);
1529        let overlay_context = overlay.context(app);
1530        let sub_key = child.key().expect("All list items must have a key").clone();
1531        ReorderableItem {
1532            key: GlobalKey::wrapping(Rc::new(ReorderableItemGlobalKey {
1533                sub_key,
1534                index,
1535                state: self.id(),
1536            }))
1537            .into(),
1538            index,
1539            captured_themes: Rc::new(<dyn InheritedTheme>::capture(
1540                app,
1541                context,
1542                Some(overlay_context),
1543            )),
1544            child: self.wrap_with_semantics(app, child, index),
1545        }
1546        .into_widget()
1547    }
1548
1549    fn wrap_with_semantics(
1550        self: Handle<Self>,
1551        app: &mut App,
1552        child: WidgetRef,
1553        index: i32,
1554    ) -> WidgetRef {
1555        // First, determine which semantics actions apply.
1556        let mut semantics_actions: IndexMap<CustomSemanticsAction, VoidCallback> = IndexMap::new();
1557
1558        // Create the appropriate semantics actions.
1559        let move_to_start: VoidCallback =
1560            Rc::new(move |app| self.handle_reorder_item(app, index, 0));
1561        let move_to_end: VoidCallback = Rc::new(move |app| {
1562            let item_count = self.widget(app).item_count;
1563            self.handle_reorder_item(app, index, item_count);
1564        });
1565        let move_before: VoidCallback =
1566            Rc::new(move |app| self.handle_reorder_item(app, index, index - 1));
1567        // To move after, go to index+2 because it is moved to the space
1568        // before index+2, which is after the space at index+1.
1569        let move_after: VoidCallback =
1570            Rc::new(move |app| self.handle_reorder_item(app, index, index + 2));
1571
1572        let context = self.context(app);
1573        let localizations = <dyn WidgetsLocalizations>::of(app, context);
1574        let is_horizontal = self.scroll_direction(app) == Axis::Horizontal;
1575        // If the item can move to before its current position in the list.
1576        if index > 0 {
1577            semantics_actions.insert(
1578                CustomSemanticsAction::new(localizations.reorder_item_to_start()),
1579                move_to_start,
1580            );
1581            let mut reorder_item_before = localizations.reorder_item_up();
1582            if is_horizontal {
1583                reorder_item_before = if Directionality::of(app, context) == TextDirection::Ltr {
1584                    localizations.reorder_item_left()
1585                } else {
1586                    localizations.reorder_item_right()
1587                };
1588            }
1589            semantics_actions.insert(CustomSemanticsAction::new(reorder_item_before), move_before);
1590        }
1591
1592        // If the item can move to after its current position in the list.
1593        if index < self.widget(app).item_count - 1 {
1594            let mut reorder_item_after = localizations.reorder_item_down();
1595            if is_horizontal {
1596                reorder_item_after = if Directionality::of(app, context) == TextDirection::Ltr {
1597                    localizations.reorder_item_right()
1598                } else {
1599                    localizations.reorder_item_left()
1600                };
1601            }
1602            semantics_actions.insert(CustomSemanticsAction::new(reorder_item_after), move_after);
1603            semantics_actions.insert(
1604                CustomSemanticsAction::new(localizations.reorder_item_to_end()),
1605                move_to_end,
1606            );
1607        }
1608
1609        // Pass toWrap with a GlobalKey into the item so that when it
1610        // gets dragged, the accessibility framework can preserve the selected
1611        // state of the dragging item.
1612        //
1613        // Also apply the relevant custom accessibility actions for moving the item
1614        // up, down, to the start, and to the end of the list.
1615        Semantics::new()
1616            .container(true)
1617            .custom_semantics_actions(semantics_actions)
1618            .child(child)
1619            .into_widget()
1620    }
1621}
1622
1623impl TickerProviderObject for SliverReorderableListState {
1624    fn create_ticker(self: Handle<Self>, app: &mut App, on_tick: TickerCallback) -> Ref<Ticker> {
1625        TickerProviderStateMixin::create_ticker(self, app, on_tick)
1626    }
1627}
1628
1629impl TickerProviderStateMixin for SliverReorderableListState {
1630    fn ticker_provider_data(self: Handle<Self>, app: &App) -> &TickerProviderStateMixinData {
1631        &app.get(self).ticker_provider
1632    }
1633
1634    fn ticker_provider_data_mut(
1635        self: Handle<Self>,
1636        app: &mut App,
1637    ) -> &mut TickerProviderStateMixinData {
1638        &mut app.get_mut(self).ticker_provider
1639    }
1640}
1641
1642impl State for SliverReorderableListState {
1643    type Widget = SliverReorderableList;
1644    crate::state_accessors!();
1645
1646    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
1647        let scrollable = Scrollable::of(app, self.context(app), None);
1648        app.get_mut(self).scrollable = Some(scrollable);
1649        let current = app
1650            .get(self)
1651            .auto_scroller
1652            .handle()
1653            .map(|auto_scroller| app.get(auto_scroller).scrollable);
1654        if current != Some(scrollable) {
1655            if let Some(auto_scroller) = app.get(self).auto_scroller.handle() {
1656                auto_scroller.stop_auto_scroll(app);
1657            }
1658            let auto_scroller = self.new_auto_scroller(app);
1659            app.get_mut(self).auto_scroller = Some(auto_scroller);
1660        }
1661    }
1662
1663    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &SliverReorderableList) {
1664        if self.widget(app).item_count != old_widget.item_count {
1665            self.cancel_reorder(app);
1666        }
1667
1668        if self.widget(app).auto_scroller_velocity_scalar
1669            != old_widget.auto_scroller_velocity_scalar
1670        {
1671            if let Some(auto_scroller) = app.get(self).auto_scroller.handle() {
1672                auto_scroller.stop_auto_scroll(app);
1673            }
1674            let auto_scroller = self.new_auto_scroller(app);
1675            app.get_mut(self).auto_scroller = Some(auto_scroller);
1676        }
1677    }
1678
1679    fn activate(self: Handle<Self>, app: &mut App) {
1680        TickerProviderStateMixin::activate(self, app);
1681    }
1682
1683    fn dispose(self: Handle<Self>, app: &mut App) {
1684        self.drag_reset(app);
1685        if let Some(recognizer) = app.get_mut(self).recognizer.take() {
1686            recognizer.dispose(app);
1687        }
1688        TickerProviderStateMixin::dispose(self, app);
1689    }
1690
1691    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1692        debug_assert!(debug_check_has_overlay(app, context));
1693        let widget = self.widget(app);
1694        let mut children_delegate = SliverChildBuilderDelegate::new(move |app, context, index| {
1695            Some(self.item_builder(app, context, index))
1696        })
1697        .child_count(widget.item_count);
1698        if let Some(find_child_index_callback) = widget.find_child_index_callback.clone() {
1699            children_delegate =
1700                children_delegate.find_child_index_callback(find_child_index_callback);
1701        }
1702        let children_delegate = children_delegate.into_delegate();
1703        if let Some(item_extent) = widget.item_extent {
1704            return SliverFixedExtentList::new(children_delegate, item_extent).into_widget();
1705        } else if let Some(item_extent_builder) = widget.item_extent_builder.clone() {
1706            return SliverVariedExtentList::new(children_delegate, item_extent_builder)
1707                .into_widget();
1708        } else if let Some(prototype_item) = widget.prototype_item.clone() {
1709            return SliverPrototypeExtentList::new(children_delegate, prototype_item).into_widget();
1710        }
1711        SliverList::new(children_delegate).into_widget()
1712    }
1713}
1714
1715/// Dart's `_ReorderableItem`.
1716#[derive(Debug)]
1717struct ReorderableItem {
1718    key: KeyRef,
1719    index: i32,
1720    child: WidgetRef,
1721    captured_themes: Rc<CapturedThemes>,
1722}
1723
1724impl StatefulWidget for ReorderableItem {
1725    type State = ReorderableItemState;
1726
1727    fn key(&self) -> Option<&KeyRef> {
1728        Some(&self.key)
1729    }
1730
1731    fn create_state(&self) -> ReorderableItemState {
1732        ReorderableItemState {
1733            state: StateData::new(),
1734            list_state: None,
1735            start_offset: Offset::ZERO,
1736            target_offset: Offset::ZERO,
1737            offset_animation: None,
1738            dragging: false,
1739        }
1740    }
1741}
1742
1743/// Dart's `_ReorderableItemState`.
1744struct ReorderableItemState {
1745    state: StateData<ReorderableItem>,
1746    // Dart's `late`: set in `init_state`.
1747    list_state: Option<Handle<SliverReorderableListState>>,
1748
1749    start_offset: Offset,
1750    target_offset: Offset,
1751    offset_animation: Option<Ref<AnimationController>>,
1752
1753    dragging: bool,
1754}
1755
1756impl ReorderableItemState {
1757    fn list_state(self: Handle<Self>, app: &App) -> Handle<SliverReorderableListState> {
1758        app.get(self).list_state.expect("set in init_state")
1759    }
1760
1761    fn index(self: Handle<Self>, app: &App) -> i32 {
1762        self.widget(app).index
1763    }
1764
1765    fn set_dragging(self: Handle<Self>, app: &mut App, dragging: bool) {
1766        if self.mounted(app) {
1767            self.set_state(app, |state| state.dragging = dragging);
1768        }
1769    }
1770
1771    fn offset(self: Handle<Self>, app: &App) -> Offset {
1772        let state = app.get(self);
1773        if let Some(offset_animation) = &state.offset_animation {
1774            let anim_value = Curves::ease_in_out().transform(offset_animation.value(app));
1775            return Offset::lerp(
1776                Some(state.start_offset),
1777                Some(state.target_offset),
1778                anim_value,
1779            )
1780            .expect("both offsets are given");
1781        }
1782        state.target_offset
1783    }
1784
1785    fn update_for_gap(
1786        self: Handle<Self>,
1787        app: &mut App,
1788        drag_index: i32,
1789        gap_index: i32,
1790        gap_extent: f64,
1791        animate: bool,
1792        reverse: bool,
1793    ) {
1794        // An offset needs to be added to create a gap when we are between the
1795        // moving element (drag_index) and the current gap position (gap_index).
1796        // For how to update the gap position, refer to `drag_update_items`.
1797        let index = self.index(app);
1798        let scroll_direction = self.list_state(app).scroll_direction(app);
1799        let new_target_offset =
1800            if gap_index < drag_index && index < drag_index && index >= gap_index {
1801                extent_offset(
1802                    if reverse { -gap_extent } else { gap_extent },
1803                    scroll_direction,
1804                )
1805            } else if gap_index > drag_index && index > drag_index && index < gap_index {
1806                extent_offset(
1807                    if reverse { gap_extent } else { -gap_extent },
1808                    scroll_direction,
1809                )
1810            } else {
1811                Offset::ZERO
1812            };
1813        if new_target_offset != app.get(self).target_offset {
1814            let previous_target = app.get(self).target_offset;
1815            app.get_mut(self).target_offset = new_target_offset;
1816            if animate {
1817                if let Some(offset_animation) = app.get(self).offset_animation.handle() {
1818                    // Animation interrupted - calculate current position from previous animation
1819                    let current_anim_value =
1820                        Curves::ease_in_out().transform(offset_animation.value(app));
1821                    let current_position = Offset::lerp(
1822                        Some(app.get(self).start_offset),
1823                        Some(previous_target),
1824                        current_anim_value,
1825                    )
1826                    .expect("both offsets are given");
1827                    app.get_mut(self).start_offset = current_position;
1828                    drop(offset_animation.forward(app, Some(0.0)));
1829                } else {
1830                    let list_state = self.list_state(app);
1831                    let offset_animation = AnimationController::new(
1832                        app,
1833                        None,
1834                        Some(Duration::from_millis(250)),
1835                        None,
1836                        0.0,
1837                        1.0,
1838                        AnimationBehavior::Normal,
1839                        list_state,
1840                    );
1841                    offset_animation
1842                        .add_listener(app, Listener::handle_method(self, Self::rebuild));
1843                    offset_animation.add_status_listener(
1844                        app,
1845                        AnimationStatusListener::new(move |status, app| {
1846                            if status.is_completed() {
1847                                let state = app.get_mut(self);
1848                                state.start_offset = state.target_offset;
1849                                if let Some(offset_animation) = state.offset_animation.take() {
1850                                    offset_animation.dispose(app);
1851                                }
1852                            }
1853                        }),
1854                    );
1855                    app.get_mut(self).offset_animation = Some(offset_animation.clone());
1856                    drop(offset_animation.forward(app, None));
1857                }
1858            } else {
1859                if let Some(offset_animation) = app.get_mut(self).offset_animation.take() {
1860                    offset_animation.dispose(app);
1861                }
1862                let state = app.get_mut(self);
1863                state.start_offset = state.target_offset;
1864            }
1865            self.rebuild(app);
1866        }
1867    }
1868
1869    fn reset_gap(self: Handle<Self>, app: &mut App) {
1870        if let Some(offset_animation) = app.get_mut(self).offset_animation.take() {
1871            offset_animation.dispose(app);
1872        }
1873        let state = app.get_mut(self);
1874        state.start_offset = Offset::ZERO;
1875        state.target_offset = Offset::ZERO;
1876        self.rebuild(app);
1877    }
1878
1879    fn target_geometry(self: Handle<Self>, app: &App) -> Rect {
1880        let item_render_box = self
1881            .context(app)
1882            .find_render_object(app)
1883            .and_then(|render_object| render_object.as_box())
1884            .expect("a reorderable item is a RenderBox");
1885        let item_position =
1886            item_render_box.local_to_global(app, Offset::ZERO, None) + app.get(self).target_offset;
1887        item_position & item_render_box.size(app)
1888    }
1889
1890    fn rebuild(self: Handle<Self>, app: &mut App) {
1891        if self.mounted(app) {
1892            self.set_state(app, |_| {});
1893        }
1894    }
1895}
1896
1897impl State for ReorderableItemState {
1898    type Widget = ReorderableItem;
1899    crate::state_accessors!();
1900
1901    fn init_state(self: Handle<Self>, app: &mut App) {
1902        let list_state = SliverReorderableList::of(app, self.context(app));
1903        app.get_mut(self).list_state = Some(list_state);
1904        list_state.register_item(app, self);
1905    }
1906
1907    fn dispose(self: Handle<Self>, app: &mut App) {
1908        if let Some(offset_animation) = app.get(self).offset_animation.handle() {
1909            offset_animation.dispose(app);
1910        }
1911        let index = self.index(app);
1912        self.list_state(app).unregister_item(app, index, self);
1913    }
1914
1915    fn did_update_widget(self: Handle<Self>, app: &mut App, old_widget: &ReorderableItem) {
1916        if old_widget.index != self.widget(app).index {
1917            let list_state = self.list_state(app);
1918            list_state.unregister_item(app, old_widget.index, self);
1919            list_state.register_item(app, self);
1920        }
1921    }
1922
1923    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1924        let list_state = self.list_state(app);
1925        if app.get(self).dragging {
1926            let item_extent = app.get(list_state.drag_info(app)).item_extent;
1927            let size = extent_size(item_extent, list_state.scroll_direction(app));
1928            return SizedBox::from_size(Some(size)).into_widget();
1929        }
1930        list_state.register_item(app, self);
1931        Transform::translate(self.offset(app))
1932            .child(self.widget(app).child.clone())
1933            .into_widget()
1934    }
1935
1936    fn deactivate(self: Handle<Self>, app: &mut App) {
1937        let index = self.index(app);
1938        self.list_state(app).unregister_item(app, index, self);
1939    }
1940}
1941
1942/// A wrapper widget that will recognize the start of a drag on the wrapped widget by a
1943/// [`PointerDownEvent`], and immediately initiate dragging the wrapped item to a new location
1944/// in a reorderable list.
1945///
1946/// See also:
1947///
1948///  * [`ReorderableDelayedDragStartListener`], a similar wrapper that will only recognize the
1949///    start after a long press event.
1950///  * [`ReorderableList`], a widget list that allows the user to reorder its items.
1951///  * [`SliverReorderableList`], a sliver list that allows the user to reorder its items.
1952///  * `ReorderableListView`, a Material Design list that allows the user to reorder its items.
1953#[derive(Clone, Debug)]
1954pub struct ReorderableDragStartListener {
1955    pub key: Option<KeyRef>,
1956
1957    /// The widget for which the application would like to respond to a tap and drag gesture
1958    /// by starting a reordering drag on a reorderable list.
1959    pub child: WidgetRef,
1960
1961    /// The index of the associated item that will be dragged in the list.
1962    pub index: i32,
1963
1964    /// Whether the [`child`](Self::child) item can be dragged and moved in the list.
1965    ///
1966    /// If true, the item can be moved to another location in the list when the user taps on
1967    /// the child. If false, tapping on the child will be ignored.
1968    pub enabled: bool,
1969}
1970
1971impl ReorderableDragStartListener {
1972    /// Creates a listener for a drag immediately following a pointer down event over the given
1973    /// child widget.
1974    ///
1975    /// This is most commonly used to wrap part of a list item like a drag handle.
1976    #[cfg_attr(debug_assertions, track_caller)]
1977    pub fn new<K>(child: impl IntoWidget<K>, index: i32) -> ReorderableDragStartListener {
1978        ReorderableDragStartListener {
1979            key: None,
1980            child: child.into_widget(),
1981            index,
1982            enabled: true,
1983        }
1984    }
1985
1986    /// Dart `ReorderableDragStartListener(key:)`.
1987    pub fn key(mut self, key: KeyRef) -> ReorderableDragStartListener {
1988        self.key = Some(key);
1989        self
1990    }
1991
1992    /// Dart `ReorderableDragStartListener(enabled:)`.
1993    pub fn enabled(mut self, enabled: bool) -> ReorderableDragStartListener {
1994        self.enabled = enabled;
1995        self
1996    }
1997}
1998
1999/// Dart's `ReorderableDragStartListener` as the base class of the listeners: a subclass, such
2000/// as [`ReorderableDelayedDragStartListener`], overrides
2001/// [`create_recognizer`](Self::create_recognizer), and its build is
2002/// [`build`](Self::build).
2003pub trait ReorderableDragStartListenerWidget: Clone + 'static {
2004    /// The base class's fields.
2005    fn reorderable_drag_start_listener(&self) -> &ReorderableDragStartListener;
2006
2007    /// Provides the gesture recognizer used to indicate the start of a reordering drag
2008    /// operation.
2009    ///
2010    /// [`ReorderableDragStartListener`] answers an [`ImmediateMultiDragGestureRecognizer`];
2011    /// a subclass customizes the drag start gesture here.
2012    fn create_recognizer(&self, app: &mut App) -> MultiDragRecognizerRef;
2013
2014    /// Dart's `ReorderableDragStartListener.build`, which every subclass inherits.
2015    fn build(&self, _app: &mut App, context: BuildContext) -> WidgetRef {
2016        let listener = self.reorderable_drag_start_listener();
2017        let mut pointer_listener = PointerListener::new().child(listener.child.clone());
2018        if listener.enabled {
2019            let this = self.clone();
2020            pointer_listener = pointer_listener.on_pointer_down(Rc::new(
2021                move |app: &mut App, event: PointerDownEvent| {
2022                    start_dragging(&this, app, context, event);
2023                },
2024            ));
2025        }
2026        pointer_listener.into_widget()
2027    }
2028}
2029
2030/// Dart's `ReorderableDragStartListener._startDragging`.
2031fn start_dragging<W: ReorderableDragStartListenerWidget>(
2032    widget: &W,
2033    app: &mut App,
2034    context: BuildContext,
2035    event: PointerDownEvent,
2036) {
2037    let gesture_settings = MediaQuery::maybe_gesture_settings_of(app, context);
2038    let list = SliverReorderableList::maybe_of(app, context);
2039    if let Some(list) = list {
2040        let recognizer = widget.create_recognizer(app);
2041        recognizer.set_gesture_settings(app, gesture_settings);
2042        let index = widget.reorderable_drag_start_listener().index;
2043        list.start_item_drag_reorder(app, index, event, recognizer);
2044    }
2045}
2046
2047impl ReorderableDragStartListenerWidget for ReorderableDragStartListener {
2048    fn reorderable_drag_start_listener(&self) -> &ReorderableDragStartListener {
2049        self
2050    }
2051
2052    fn create_recognizer(&self, app: &mut App) -> MultiDragRecognizerRef {
2053        ImmediateMultiDragGestureRecognizer::new(app).into_erased()
2054    }
2055}
2056
2057impl StatelessWidget for ReorderableDragStartListener {
2058    fn key(&self) -> Option<&KeyRef> {
2059        self.key.as_ref()
2060    }
2061
2062    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2063        ReorderableDragStartListenerWidget::build(self, app, context)
2064    }
2065}
2066
2067/// A wrapper widget that will recognize the start of a drag operation by looking for a long
2068/// press event. Once it is recognized, it will start a drag operation on the wrapped item in
2069/// the reorderable list.
2070///
2071/// See also:
2072///
2073///  * [`ReorderableDragStartListener`], a similar wrapper that will recognize the start of the
2074///    drag immediately after a pointer down event.
2075///  * [`ReorderableList`], a widget list that allows the user to reorder its items.
2076///  * [`SliverReorderableList`], a sliver list that allows the user to reorder its items.
2077///  * `ReorderableListView`, a Material Design list that allows the user to reorder its items.
2078#[derive(Clone, Debug)]
2079pub struct ReorderableDelayedDragStartListener {
2080    /// The [`ReorderableDragStartListener`] superclass fields.
2081    pub listener: ReorderableDragStartListener,
2082}
2083
2084impl ReorderableDelayedDragStartListener {
2085    /// Creates a listener for an drag following a long press event over the given child
2086    /// widget.
2087    ///
2088    /// This is most commonly used to wrap an entire list item in a reorderable list.
2089    #[cfg_attr(debug_assertions, track_caller)]
2090    pub fn new<K>(child: impl IntoWidget<K>, index: i32) -> ReorderableDelayedDragStartListener {
2091        ReorderableDelayedDragStartListener {
2092            listener: ReorderableDragStartListener::new(child, index),
2093        }
2094    }
2095
2096    /// Dart `ReorderableDelayedDragStartListener(key:)`.
2097    pub fn key(mut self, key: KeyRef) -> ReorderableDelayedDragStartListener {
2098        self.listener.key = Some(key);
2099        self
2100    }
2101
2102    /// Dart `ReorderableDelayedDragStartListener(enabled:)`.
2103    pub fn enabled(mut self, enabled: bool) -> ReorderableDelayedDragStartListener {
2104        self.listener.enabled = enabled;
2105        self
2106    }
2107}
2108
2109impl ReorderableDragStartListenerWidget for ReorderableDelayedDragStartListener {
2110    fn reorderable_drag_start_listener(&self) -> &ReorderableDragStartListener {
2111        &self.listener
2112    }
2113
2114    fn create_recognizer(&self, app: &mut App) -> MultiDragRecognizerRef {
2115        DelayedMultiDragGestureRecognizer::new(app).into_erased()
2116    }
2117}
2118
2119impl StatelessWidget for ReorderableDelayedDragStartListener {
2120    fn key(&self) -> Option<&KeyRef> {
2121        self.listener.key.as_ref()
2122    }
2123
2124    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2125        ReorderableDragStartListenerWidget::build(self, app, context)
2126    }
2127}
2128
2129/// Dart's `_DragItemUpdate`.
2130type DragItemUpdate = Rc<dyn Fn(&mut App, Handle<DragInfo>, Offset, Offset)>;
2131
2132/// Dart's `_DragItemCallback`.
2133type DragItemCallback = Rc<dyn Fn(&mut App, Handle<DragInfo>)>;
2134
2135/// Dart's `_DragInfo`: the [`Drag`] the recognizer reports an item drag's moves to.
2136struct DragInfo {
2137    scroll_direction: Axis,
2138    on_update: Option<DragItemUpdate>,
2139    on_end: Option<DragItemCallback>,
2140    on_cancel: Option<DragItemCallback>,
2141    on_drop_completed: Option<VoidCallback>,
2142    proxy_decorator: Option<ReorderItemProxyDecorator>,
2143    ticker_provider: Rc<dyn TickerProvider>,
2144
2145    boundary: Option<Box<dyn DragBoundaryDelegate<Rect>>>,
2146    list_state: Handle<SliverReorderableListState>,
2147    index: i32,
2148    child: WidgetRef,
2149    drag_position: Offset,
2150    drag_offset: Offset,
2151    item_size: Size,
2152    item_layout_constraints: BoxConstraints,
2153    item_extent: f64,
2154    captured_themes: Rc<CapturedThemes>,
2155    #[expect(dead_code, reason = "Dart's field, which nothing in the file reads")]
2156    scrollable: Option<Handle<ScrollableState>>,
2157    proxy_animation: Option<Ref<AnimationController>>,
2158    raw_drag_position: Offset,
2159}
2160
2161impl DragInfo {
2162    #[expect(
2163        clippy::too_many_arguments,
2164        reason = "Dart's named constructor arguments, all of which its one caller passes"
2165    )]
2166    fn new(
2167        app: &mut App,
2168        item: Handle<ReorderableItemState>,
2169        initial_position: Offset,
2170        scroll_direction: Axis,
2171        on_update: Option<DragItemUpdate>,
2172        on_end: Option<DragItemCallback>,
2173        on_cancel: Option<DragItemCallback>,
2174        on_drop_completed: Option<VoidCallback>,
2175        proxy_decorator: Option<ReorderItemProxyDecorator>,
2176        ticker_provider: Rc<dyn TickerProvider>,
2177    ) -> Ref<DragInfo> {
2178        let item_context = item.context(app);
2179        let item_render_box = item_context
2180            .find_render_object(app)
2181            .and_then(|render_object| render_object.as_box())
2182            .expect("a reorderable item is a RenderBox");
2183        let list_state = item.list_state(app);
2184        let index = item.index(app);
2185        let child = item.widget(app).child.clone();
2186        let captured_themes = Rc::clone(&item.widget(app).captured_themes);
2187        let drag_offset = item_render_box.global_to_local(app, initial_position, None);
2188        let item_size = item_context.size(app).expect("a laid-out item");
2189        let raw_drag_position = initial_position;
2190        let list_context = list_state.context(app);
2191        let boundary = match list_state.widget(app).drag_boundary_provider.clone() {
2192            Some(drag_boundary_provider) => drag_boundary_provider(app, list_context),
2193            None => DragBoundary::for_rect_maybe_of(app, list_context, true),
2194        };
2195        let drag_position = adjusted_drag_offset(
2196            boundary.as_deref(),
2197            drag_offset,
2198            item_size,
2199            initial_position,
2200        );
2201        let item_extent = size_extent(item_size, scroll_direction);
2202        let item_layout_constraints = item_render_box.constraints(app);
2203        let scrollable = Some(Scrollable::of(app, item_context, None));
2204        let this = app.create(DragInfo {
2205            scroll_direction,
2206            on_update,
2207            on_end,
2208            on_cancel,
2209            on_drop_completed,
2210            proxy_decorator,
2211            ticker_provider,
2212            boundary,
2213            list_state,
2214            index,
2215            child,
2216            drag_position,
2217            drag_offset,
2218            item_size,
2219            item_layout_constraints,
2220            item_extent,
2221            captured_themes,
2222            scrollable,
2223            proxy_animation: None,
2224            raw_drag_position,
2225        });
2226        app.expect_dispose(&this);
2227        this
2228    }
2229
2230    fn dispose(self: Handle<Self>, app: &mut App) {
2231        app.mark_disposed(self);
2232        if let Some(proxy_animation) = app.get(self).proxy_animation.handle() {
2233            proxy_animation.dispose(app);
2234        }
2235    }
2236
2237    fn start_drag(self: Handle<Self>, app: &mut App) {
2238        let ticker_provider = Rc::clone(&app.get(self).ticker_provider);
2239        let proxy_animation = AnimationController::new(
2240            app,
2241            None,
2242            Some(Duration::from_millis(250)),
2243            None,
2244            0.0,
2245            1.0,
2246            AnimationBehavior::Normal,
2247            ticker_provider,
2248        );
2249        proxy_animation.add_status_listener(
2250            app,
2251            AnimationStatusListener::new(move |status, app| {
2252                if status.is_dismissed() {
2253                    self.drop_completed(app);
2254                }
2255            }),
2256        );
2257        app.get_mut(self).proxy_animation = Some(proxy_animation.clone());
2258        drop(proxy_animation.forward(app, None));
2259    }
2260
2261    fn adjusted_drag_offset(self: Handle<Self>, app: &App, offset: Offset) -> Offset {
2262        let info = app.get(self);
2263        adjusted_drag_offset(
2264            info.boundary.as_deref(),
2265            info.drag_offset,
2266            info.item_size,
2267            offset,
2268        )
2269    }
2270
2271    fn drop_completed(self: Handle<Self>, app: &mut App) {
2272        if let Some(proxy_animation) = app.get_mut(self).proxy_animation.take() {
2273            proxy_animation.dispose(app);
2274        }
2275        if let Some(on_drop_completed) = app.get(self).on_drop_completed.clone() {
2276            on_drop_completed(app);
2277        }
2278    }
2279
2280    fn create_proxy(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
2281        let position =
2282            app.get(self).drag_position - app.get(self).drag_offset - overlay_origin(app, context);
2283        let info = app.get(self);
2284        info.captured_themes.wrap(
2285            DragItemProxy {
2286                list_state: info.list_state,
2287                index: info.index,
2288                child: info.child.clone(),
2289                position,
2290                size: info.item_size,
2291                constraints: info.item_layout_constraints,
2292                animation: info
2293                    .proxy_animation
2294                    .clone()
2295                    .expect("the drag started its proxy animation"),
2296                proxy_decorator: info.proxy_decorator.clone(),
2297            }
2298            .into_widget(),
2299        )
2300    }
2301}
2302
2303/// Dart's `_DragInfo._adjustedDragOffset`, over the fields it reads, so the constructor can
2304/// call it before the object exists.
2305fn adjusted_drag_offset(
2306    boundary: Option<&dyn DragBoundaryDelegate<Rect>>,
2307    drag_offset: Offset,
2308    item_size: Size,
2309    offset: Offset,
2310) -> Offset {
2311    let Some(boundary) = boundary else {
2312        return offset;
2313    };
2314    boundary
2315        .nearest_position_within_boundary((offset - drag_offset) & item_size)
2316        .shift(drag_offset)
2317        .top_left()
2318}
2319
2320impl DragObject for DragInfo {
2321    fn update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
2322        let delta = restrict_axis(details.delta, app.get(self).scroll_direction);
2323        let raw_drag_position = app.get(self).raw_drag_position + delta;
2324        app.get_mut(self).raw_drag_position = raw_drag_position;
2325        let drag_position = self.adjusted_drag_offset(app, raw_drag_position);
2326        app.get_mut(self).drag_position = drag_position;
2327        if let Some(on_update) = app.get(self).on_update.clone() {
2328            on_update(app, self, drag_position, details.delta);
2329        }
2330    }
2331
2332    fn end(self: Handle<Self>, app: &mut App, _details: DragEndDetails) {
2333        let proxy_animation = app
2334            .get(self)
2335            .proxy_animation
2336            .handle()
2337            .expect("the drag started its proxy animation");
2338        drop(proxy_animation.reverse(app, None));
2339        if let Some(on_end) = app.get(self).on_end.clone() {
2340            on_end(app, self);
2341        }
2342    }
2343
2344    fn cancel(self: Handle<Self>, app: &mut App) {
2345        if let Some(proxy_animation) = app.get_mut(self).proxy_animation.take() {
2346            proxy_animation.dispose(app);
2347        }
2348        if let Some(on_cancel) = app.get(self).on_cancel.clone() {
2349            on_cancel(app, self);
2350        }
2351    }
2352}
2353
2354/// Dart's `_overlayOrigin`.
2355fn overlay_origin(app: &mut App, context: BuildContext) -> Offset {
2356    let overlay = Overlay::of(app, context, false);
2357    let overlay_box = overlay
2358        .context(app)
2359        .find_render_object(app)
2360        .and_then(|render_object| render_object.as_box())
2361        .expect("an Overlay's render object is a RenderBox");
2362    overlay_box.local_to_global(app, Offset::ZERO, None)
2363}
2364
2365/// Dart's `_DragItemProxy`.
2366struct DragItemProxy {
2367    list_state: Handle<SliverReorderableListState>,
2368    index: i32,
2369    child: WidgetRef,
2370    position: Offset,
2371    size: Size,
2372    constraints: BoxConstraints,
2373    animation: Ref<AnimationController>,
2374    proxy_decorator: Option<ReorderItemProxyDecorator>,
2375}
2376
2377impl Debug for DragItemProxy {
2378    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2379        f.debug_struct("DragItemProxy")
2380            .field("index", &self.index)
2381            .field("position", &self.position)
2382            .field("size", &self.size)
2383            .finish_non_exhaustive()
2384    }
2385}
2386
2387impl StatelessWidget for DragItemProxy {
2388    fn build(&self, app: &mut App, context: BuildContext) -> WidgetRef {
2389        let proxy_child = match &self.proxy_decorator {
2390            Some(proxy_decorator) => {
2391                proxy_decorator(app, self.child.clone(), self.index, self.animation.erase())
2392            }
2393            None => self.child.clone(),
2394        };
2395        let overlay_origin = overlay_origin(app, context);
2396
2397        let list_state = self.list_state;
2398        let position = self.position;
2399        let size = self.size;
2400        let constraints = self.constraints;
2401        let animation = self.animation.handle();
2402        let listenable: Rc<dyn Listenable> = Rc::new(self.animation.clone());
2403        MediaQuery::new(
2404            // Remove the top padding so that any nested list views in the item
2405            // won't pick up the scaffold's padding in the overlay.
2406            MediaQuery::of(app, context).remove_padding(false, true, false, false),
2407            AnimatedBuilder::new(listenable, move |app, _context, child| {
2408                let mut effective_position = position;
2409                let drop_position = app.get(list_state).final_drop_position;
2410                if let Some(drop_position) = drop_position {
2411                    effective_position = Offset::lerp(
2412                        Some(drop_position - overlay_origin),
2413                        Some(effective_position),
2414                        Curves::ease_out().transform(animation.value(app)),
2415                    )
2416                    .expect("both offsets are given");
2417                }
2418                let mut overflow_box = OverflowBox::new()
2419                    .min_width(constraints.min_width)
2420                    .min_height(constraints.min_height)
2421                    .max_width(constraints.max_width)
2422                    .max_height(constraints.max_height)
2423                    .alignment(if list_state.scroll_direction(app) == Axis::Horizontal {
2424                        AlignmentGeometry::CENTER_LEFT
2425                    } else {
2426                        AlignmentGeometry::TOP_CENTER
2427                    });
2428                if let Some(child) = child {
2429                    overflow_box = overflow_box.child(child.clone());
2430                }
2431                Positioned::new(
2432                    SizedBox::new()
2433                        .width(size.width())
2434                        .height(size.height())
2435                        .child(overflow_box),
2436                )
2437                .left(effective_position.dx())
2438                .top(effective_position.dy())
2439                .into_widget()
2440            })
2441            .child(proxy_child),
2442        )
2443        .into_widget()
2444    }
2445}
2446
2447fn size_extent(size: Size, scroll_direction: Axis) -> f64 {
2448    match scroll_direction {
2449        Axis::Horizontal => size.width(),
2450        Axis::Vertical => size.height(),
2451    }
2452}
2453
2454fn extent_size(extent: f64, scroll_direction: Axis) -> Size {
2455    match scroll_direction {
2456        Axis::Horizontal => Size::new(extent, 0.0),
2457        Axis::Vertical => Size::new(0.0, extent),
2458    }
2459}
2460
2461fn offset_extent(offset: Offset, scroll_direction: Axis) -> f64 {
2462    match scroll_direction {
2463        Axis::Horizontal => offset.dx(),
2464        Axis::Vertical => offset.dy(),
2465    }
2466}
2467
2468fn extent_offset(extent: f64, scroll_direction: Axis) -> Offset {
2469    match scroll_direction {
2470        Axis::Horizontal => Offset::new(extent, 0.0),
2471        Axis::Vertical => Offset::new(0.0, extent),
2472    }
2473}
2474
2475fn restrict_axis(offset: Offset, scroll_direction: Axis) -> Offset {
2476    match scroll_direction {
2477        Axis::Horizontal => Offset::new(offset.dx(), 0.0),
2478        Axis::Vertical => Offset::new(0.0, offset.dy()),
2479    }
2480}
2481
2482/// Dart's `_ReorderableItemGlobalKey`: a global key that takes its identity from the object
2483/// and uses a value of a particular type to identify itself.
2484///
2485/// The difference with `GlobalObjectKey` is that it uses `==` instead of `identical` of the
2486/// objects used to generate widgets.
2487#[derive(Debug)]
2488struct ReorderableItemGlobalKey {
2489    sub_key: KeyRef,
2490    index: i32,
2491    state: HandleId,
2492}
2493
2494impl Key for ReorderableItemGlobalKey {
2495    fn eq_key(&self, other: &dyn Key) -> bool {
2496        (other as &dyn Any)
2497            .downcast_ref::<ReorderableItemGlobalKey>()
2498            .is_some_and(|other| {
2499                other.sub_key == self.sub_key
2500                    && other.index == self.index
2501                    && other.state == self.state
2502            })
2503    }
2504
2505    fn hash_key(&self, mut state: &mut dyn Hasher) {
2506        TypeId::of::<ReorderableItemGlobalKey>().hash(&mut state);
2507        self.sub_key.hash(&mut state);
2508        self.index.hash(&mut state);
2509        self.state.hash(&mut state);
2510    }
2511}
2512
2513#[cfg(test)]
2514mod tests {
2515    use std::cell::{Cell, RefCell};
2516    use std::collections::HashMap;
2517
2518    use waft_animation::{Drive, Tween};
2519    use waft_embedder::Color;
2520    use waft_foundation::ValueKey;
2521    use waft_gestures::{DeviceGestureSettings, K_LONG_PRESS_TIMEOUT, K_PRESS_TIMEOUT};
2522    use waft_painting::{EdgeInsets, TextStyle};
2523    use waft_rendering::CrossAxisAlignment;
2524
2525    use super::*;
2526    use crate::testing::{
2527        TestPointer, TestWidgetsApp, WidgetTester, expect, find, finds_nothing, finds_one_widget,
2528        test_widgets,
2529    };
2530    use crate::widgets::basic::{
2531        Align, Center, Column, Expanded, Row, SizedBox, StateSetter, StatefulBuilder,
2532    };
2533    use crate::widgets::container::Container;
2534    use crate::widgets::gesture_detector::GestureDetector;
2535    use crate::widgets::icon::Icon;
2536    use crate::widgets::icon_data::IconData;
2537    use crate::widgets::icon_theme::IconTheme;
2538    use crate::widgets::icon_theme_data::IconThemeData;
2539    use crate::widgets::layout_builder::LayoutBuilder;
2540    use crate::widgets::media_query::MediaQueryData;
2541    use crate::widgets::scroll_controller::ScrollController;
2542    use crate::widgets::scroll_physics::ClampingScrollPhysics;
2543    use crate::widgets::scroll_view::ListView;
2544    use crate::widgets::text::{DefaultTextStyle, RichText, Text};
2545    use crate::widgets::transitions::FadeTransition;
2546
2547    const K_RED_COLOR: Color = Color::new(0xFFFF0000);
2548    const K_GREEN_COLOR: Color = Color::new(0xFF00FF00);
2549
2550    fn k_drag_handle_icon_data() -> IconData {
2551        IconData::new(0xe25d).font_family("MaterialIcons")
2552    }
2553
2554    /// The list a case reorders, shared with its callbacks.
2555    type Items = Rc<RefCell<Vec<i32>>>;
2556
2557    /// Dart's `List<int>.generate(count, (int index) => index)`.
2558    fn items(count: i32) -> Items {
2559        Rc::new(RefCell::new((0..count).collect()))
2560    }
2561
2562    /// Dart's `items.insert(toIndex, items.removeAt(fromIndex))`, counting the calls.
2563    fn handle_reorder(
2564        items: &Items,
2565        calls: &Rc<Cell<i32>>,
2566    ) -> impl Fn(&mut App, i32, i32) + 'static {
2567        let items = Rc::clone(items);
2568        let calls = Rc::clone(calls);
2569        move |_app, from_index, to_index| {
2570            calls.set(calls.get() + 1);
2571            let mut items = items.borrow_mut();
2572            let item = items.remove(from_index as usize);
2573            items.insert(to_index as usize, item);
2574        }
2575    }
2576
2577    /// Dart's `tester.startGesture(at)`.
2578    fn start_gesture(tester: &mut WidgetTester, at: Offset) -> TestPointer {
2579        let mut pointer = TestPointer::touch(tester.next_pointer());
2580        tester.down(&mut pointer, at);
2581        pointer
2582    }
2583
2584    /// The cases' `SizedBox(key: ValueKey<int>(items[index]), height: 100, child: listener)`,
2585    /// the listener over `Text('item ${items[index]}')`.
2586    fn sized_item(
2587        items: &Items,
2588        delayed: bool,
2589        enabled: bool,
2590    ) -> impl Fn(&mut App, BuildContext, i32) -> WidgetRef + 'static {
2591        let items = Rc::clone(items);
2592        move |_app, _context, index| {
2593            let item = items.borrow()[index as usize];
2594            let text = Text::new(format!("item {item}"));
2595            let listener = if delayed {
2596                ReorderableDelayedDragStartListener::new(text, index)
2597                    .enabled(enabled)
2598                    .into_widget()
2599            } else {
2600                ReorderableDragStartListener::new(text, index)
2601                    .enabled(enabled)
2602                    .into_widget()
2603            };
2604            SizedBox::new()
2605                .key(ValueKey::new(item).into())
2606                .height(100.0)
2607                .child(listener)
2608                .into_widget()
2609        }
2610    }
2611
2612    /// Dart's `TestListTile` from `list_tile_tester.dart`, without `onTap`.
2613    fn test_list_tile<K>(title: impl IntoWidget<K>) -> WidgetRef {
2614        Container::new()
2615            .constraints(BoxConstraints::new().min_height(56.0))
2616            .padding(EdgeInsetsGeometry::symmetric(4.0, 16.0))
2617            .child(title)
2618            .into_widget()
2619    }
2620
2621    /// Dart's `TestList` widget's arguments besides `items`.
2622    #[derive(Default)]
2623    struct TestList {
2624        text_color: Option<Color>,
2625        icon_color: Option<Color>,
2626        proxy_decorator: Option<ReorderItemProxyDecorator>,
2627        reverse: bool,
2628        on_reorder_start: Option<ReorderIndexCallback>,
2629        on_reorder_end: Option<ReorderIndexCallback>,
2630    }
2631
2632    /// Dart's `TestList(items: items, ..)`: 800x100 items of alternating colours, each a row of
2633    /// `Text('item $item')` and a drag-handle icon under a `ReorderableDragStartListener`.
2634    fn test_list(items: &Items, options: TestList) -> WidgetRef {
2635        let items = Rc::clone(items);
2636        let TestList {
2637            text_color,
2638            icon_color,
2639            proxy_decorator,
2640            reverse,
2641            on_reorder_start,
2642            on_reorder_end,
2643        } = options;
2644        let mut style = TextStyle::new();
2645        if let Some(text_color) = text_color {
2646            style = style.color(text_color);
2647        }
2648        let mut icon_theme_data = IconThemeData::new();
2649        if let Some(icon_color) = icon_color {
2650            icon_theme_data = icon_theme_data.color(icon_color);
2651        }
2652        TestWidgetsApp::new()
2653            .home(DefaultTextStyle::new(
2654                style,
2655                IconTheme::new(
2656                    icon_theme_data,
2657                    StatefulBuilder::new(move |_app, _outer_context, set_state: StateSetter| {
2658                        let builder_items = Rc::clone(&items);
2659                        let reorder_items = Rc::clone(&items);
2660                        let item_count = items.borrow().len() as i32;
2661                        let mut list = SliverReorderableList::new(
2662                            move |_app, _context, index| {
2663                                let item = builder_items.borrow()[index as usize];
2664                                Container::new()
2665                                    .key(ValueKey::new(item).into())
2666                                    .height(100.0)
2667                                    .color(if item % 2 == 1 {
2668                                        K_RED_COLOR
2669                                    } else {
2670                                        K_GREEN_COLOR
2671                                    })
2672                                    .child(ReorderableDragStartListener::new(
2673                                        Row::new()
2674                                            .cross_axis_alignment(CrossAxisAlignment::Start)
2675                                            .children([
2676                                                Text::new(format!("item {item}")).into_widget(),
2677                                                Icon::new(Some(k_drag_handle_icon_data()))
2678                                                    .into_widget(),
2679                                            ]),
2680                                        index,
2681                                    ))
2682                                    .into_widget()
2683                            },
2684                            item_count,
2685                        )
2686                        .on_reorder_item(
2687                            move |app, from_index, to_index| {
2688                                let items = Rc::clone(&reorder_items);
2689                                set_state(app, &mut |_app| {
2690                                    let mut items = items.borrow_mut();
2691                                    let item = items.remove(from_index as usize);
2692                                    items.insert(to_index as usize, item);
2693                                });
2694                            },
2695                        );
2696                        list.proxy_decorator = proxy_decorator.clone();
2697                        list.on_reorder_start = on_reorder_start.clone();
2698                        list.on_reorder_end = on_reorder_end.clone();
2699                        CustomScrollView::new()
2700                            .reverse(reverse)
2701                            .slivers([list.into_widget()])
2702                            .into_widget()
2703                    }),
2704                ),
2705            ))
2706            .into_widget()
2707    }
2708
2709    #[test]
2710    fn sliver_reorderable_list_works_well_when_having_gesture_settings() {
2711        test_widgets(|tester| {
2712            // Regression test for https://github.com/flutter/flutter/issues/103404
2713            let item_count = 5;
2714            let on_reorder_call_count = Rc::new(Cell::new(0));
2715            let items = items(item_count);
2716
2717            // The list has five elements of height 100
2718            tester.pump_widget(
2719                TestWidgetsApp::new().home(
2720                    MediaQuery::new(
2721                        MediaQueryData::new()
2722                            .gesture_settings(DeviceGestureSettings::new(Some(8.0))),
2723                        CustomScrollView::new()
2724                            .slivers([SliverReorderableList::new(
2725                                sized_item(&items, false, true),
2726                                item_count,
2727                            )
2728                            .on_reorder_item(handle_reorder(&items, &on_reorder_call_count))
2729                            .into_widget()])
2730                            .into_widget(),
2731                    )
2732                    .into_widget(),
2733                ),
2734            );
2735
2736            // Start gesture on first item
2737            let at = tester.get_center(find::text("item 0"));
2738            let mut drag = start_gesture(tester, at);
2739            tester.pump_by(K_PRESS_TIMEOUT);
2740
2741            // Drag a little bit to make `ImmediateMultiDragGestureRecognizer` compete with
2742            // `VerticalDragGestureRecognizer`
2743            tester.move_by(&mut drag, Offset::new(0.0, 10.0), true);
2744            tester.pump();
2745            // Drag enough to move down the first item
2746            tester.move_by(&mut drag, Offset::new(0.0, 40.0), true);
2747            tester.pump();
2748            tester.up(&drag);
2749            tester.pump_and_settle();
2750
2751            assert_eq!(on_reorder_call_count.get(), 1);
2752            assert_eq!(*items.borrow(), vec![1, 0, 2, 3, 4]);
2753        });
2754    }
2755
2756    // Regression test for https://github.com/flutter/flutter/issues/100451
2757    #[test]
2758    fn sliver_reorderable_list_builder_respects_find_child_index_callback() {
2759        test_widgets(|tester| {
2760            let finder_called = Rc::new(Cell::new(false));
2761            let item_count = Rc::new(Cell::new(7));
2762            let state_setter: Rc<RefCell<Option<StateSetter>>> = Rc::default();
2763
2764            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new({
2765                let finder_called = Rc::clone(&finder_called);
2766                let item_count = Rc::clone(&item_count);
2767                let state_setter = Rc::clone(&state_setter);
2768                move |_app, _context, set_state| {
2769                    *state_setter.borrow_mut() = Some(set_state);
2770                    let finder_called = Rc::clone(&finder_called);
2771                    CustomScrollView::new()
2772                        .slivers([SliverReorderableList::new(
2773                            |_app, _context, index| {
2774                                Container::new()
2775                                    .key(ValueKey::new(format!("{index}")).into())
2776                                    .height(2000.0)
2777                                    .into_widget()
2778                            },
2779                            item_count.get(),
2780                        )
2781                        .find_child_index_callback(move |_key| {
2782                            finder_called.set(true);
2783                            None
2784                        })
2785                        .on_reorder_item(|_app, _from, _to| {})
2786                        .into_widget()])
2787                        .into_widget()
2788                }
2789            })));
2790            assert!(!finder_called.get());
2791
2792            // Trigger update.
2793            let set_state = state_setter.borrow().clone().expect("built");
2794            tester.update(|app| set_state(app, &mut |_app| item_count.set(77)));
2795            tester.pump();
2796
2797            assert!(finder_called.get());
2798        });
2799    }
2800
2801    // Regression test for https://github.com/flutter/flutter/issues/88191
2802    #[test]
2803    fn do_not_crash_when_dragging_with_two_fingers_simultaneously() {
2804        test_widgets(|tester| {
2805            let items = items(3);
2806            let calls = Rc::new(Cell::new(0));
2807
2808            let builder_items = Rc::clone(&items);
2809            tester.pump_widget(
2810                TestWidgetsApp::new().home(
2811                    ReorderableList::new(
2812                        move |_app, _context, index| {
2813                            let item = builder_items.borrow()[index as usize];
2814                            ReorderableDragStartListener::new(
2815                                SizedBox::new().height(100.0).child(
2816                                    Row::new()
2817                                        .cross_axis_alignment(CrossAxisAlignment::Start)
2818                                        .children(
2819                                            [Text::new(format!("item {item}")).into_widget()],
2820                                        ),
2821                                ),
2822                                index,
2823                            )
2824                            .key(ValueKey::new(item).into())
2825                            .into_widget()
2826                        },
2827                        3,
2828                    )
2829                    .on_reorder_item(handle_reorder(&items, &calls)),
2830                ),
2831            );
2832
2833            let at = tester.get_center(find::text("item 0"));
2834            let mut drag1 = start_gesture(tester, at);
2835            let mut drag2 = start_gesture(tester, at);
2836            tester.pump_by(K_LONG_PRESS_TIMEOUT);
2837
2838            tester.move_by(&mut drag1, Offset::new(0.0, 100.0), true);
2839            tester.move_by(&mut drag2, Offset::new(0.0, 100.0), true);
2840            tester.pump_and_settle();
2841
2842            tester.up(&drag1);
2843            tester.up(&drag2);
2844            tester.pump_and_settle();
2845        });
2846    }
2847
2848    #[test]
2849    #[should_panic(expected = "item_count >= 0")]
2850    fn negative_item_count_should_assert() {
2851        test_widgets(|tester| {
2852            let items = Rc::new(RefCell::new(vec![1, 2, 3]));
2853            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
2854                move |_app, _outer_context, _set_state| {
2855                    let items = Rc::clone(&items);
2856                    CustomScrollView::new()
2857                        .slivers([SliverReorderableList::new(
2858                            move |_app, _context, index| {
2859                                SizedBox::new()
2860                                    .height(100.0)
2861                                    .child(Text::new(format!(
2862                                        "item {}",
2863                                        items.borrow()[index as usize]
2864                                    )))
2865                                    .into_widget()
2866                            },
2867                            -1,
2868                        )
2869                        .on_reorder_item(|_app, _from, _to| {})
2870                        .into_widget()])
2871                        .into_widget()
2872                },
2873            )));
2874        });
2875    }
2876
2877    #[test]
2878    fn zero_item_count_should_not_build_widget() {
2879        test_widgets(|tester| {
2880            let items = Rc::new(RefCell::new(vec![1, 2, 3]));
2881            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
2882                move |_app, _outer_context, _set_state| {
2883                    let items = Rc::clone(&items);
2884                    CustomScrollView::new()
2885                        .slivers([
2886                            SliverFixedExtentList::list(
2887                                vec![Text::new("before").into_widget()],
2888                                50.0,
2889                            )
2890                            .build()
2891                            .into_widget(),
2892                            SliverReorderableList::new(
2893                                move |_app, _context, index| {
2894                                    SizedBox::new()
2895                                        .height(100.0)
2896                                        .child(Text::new(format!(
2897                                            "item {}",
2898                                            items.borrow()[index as usize]
2899                                        )))
2900                                        .into_widget()
2901                                },
2902                                0,
2903                            )
2904                            .on_reorder_item(|_app, _from, _to| {})
2905                            .into_widget(),
2906                            SliverFixedExtentList::list(
2907                                vec![Text::new("after").into_widget()],
2908                                50.0,
2909                            )
2910                            .build()
2911                            .into_widget(),
2912                        ])
2913                        .into_widget()
2914                },
2915            )));
2916
2917            expect(tester, &find::text("before"), finds_one_widget());
2918            expect(
2919                tester,
2920                &find::by_type::<SliverReorderableList>(),
2921                finds_nothing(),
2922            );
2923            expect(tester, &find::text("after"), finds_one_widget());
2924        });
2925    }
2926
2927    /// The fixed-height case's `pressDragRelease`.
2928    fn press_drag_release_settle(tester: &mut WidgetTester, start: Offset, delta: Offset) {
2929        let mut drag = start_gesture(tester, start);
2930        tester.pump_by(K_PRESS_TIMEOUT);
2931        tester.move_by(&mut drag, delta, true);
2932        tester.pump_by(K_PRESS_TIMEOUT);
2933        tester.up(&drag);
2934        tester.pump_and_settle();
2935    }
2936
2937    /// The fixed-height case's `check`.
2938    fn check(tester: &WidgetTester, visible: &[i32], hidden: &[i32]) {
2939        for i in visible {
2940            expect(
2941                tester,
2942                &find::text(&format!("item {i}")),
2943                finds_one_widget(),
2944            );
2945        }
2946        for i in hidden {
2947            expect(tester, &find::text(&format!("item {i}")), finds_nothing());
2948        }
2949    }
2950
2951    #[test]
2952    fn sliver_reorderable_list_drag_and_drop_fixed_height_items() {
2953        test_widgets(|tester| {
2954            let items = items(8);
2955
2956            // The SliverReorderableList is 800x600, 8 items, each item is 800x100 with
2957            // an "item $index" text widget at the item's origin.  Drags are initiated by
2958            // a simple press on the text widget.
2959            tester.pump_widget(test_list(&items, TestList::default()));
2960            check(tester, &[0, 1, 2, 3, 4, 5], &[6, 7]);
2961
2962            // Drag item 0 downwards less than halfway and let it snap back. List
2963            // should remain as it is.
2964            press_drag_release_settle(tester, Offset::new(12.0, 50.0), Offset::new(12.0, 60.0));
2965            check(tester, &[0, 1, 2, 3, 4, 5], &[6, 7]);
2966            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
2967            assert_eq!(
2968                tester.get_top_left(find::text("item 1")),
2969                Offset::new(0.0, 100.0)
2970            );
2971            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4, 5, 6, 7]);
2972
2973            // Drag item 0 downwards more than halfway to displace item 1.
2974            let start = tester.get_center(find::text("item 0"));
2975            press_drag_release_settle(tester, start, Offset::new(0.0, 51.0));
2976            check(tester, &[0, 1, 2, 3, 4, 5], &[6, 7]);
2977            assert_eq!(tester.get_top_left(find::text("item 1")), Offset::ZERO);
2978            assert_eq!(
2979                tester.get_top_left(find::text("item 0")),
2980                Offset::new(0.0, 100.0)
2981            );
2982            assert_eq!(*items.borrow(), vec![1, 0, 2, 3, 4, 5, 6, 7]);
2983
2984            // Drag item 0 back to where it was.
2985            let start = tester.get_center(find::text("item 0"));
2986            press_drag_release_settle(tester, start, Offset::new(0.0, -51.0));
2987            check(tester, &[0, 1, 2, 3, 4, 5], &[6, 7]);
2988            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
2989            assert_eq!(
2990                tester.get_top_left(find::text("item 1")),
2991                Offset::new(0.0, 100.0)
2992            );
2993            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4, 5, 6, 7]);
2994
2995            // Drag item 1 to item 3
2996            let start = tester.get_center(find::text("item 1"));
2997            press_drag_release_settle(tester, start, Offset::new(0.0, 151.0));
2998            check(tester, &[0, 1, 2, 3, 4, 5], &[6, 7]);
2999            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3000            assert_eq!(
3001                tester.get_top_left(find::text("item 1")),
3002                Offset::new(0.0, 300.0)
3003            );
3004            assert_eq!(
3005                tester.get_top_left(find::text("item 3")),
3006                Offset::new(0.0, 200.0)
3007            );
3008            assert_eq!(*items.borrow(), vec![0, 2, 3, 1, 4, 5, 6, 7]);
3009
3010            // Drag item 1 back to where it was
3011            let start = tester.get_center(find::text("item 1"));
3012            press_drag_release_settle(tester, start, Offset::new(0.0, -200.0));
3013            check(tester, &[0, 1, 2, 3, 4, 5], &[6, 7]);
3014            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3015            assert_eq!(
3016                tester.get_top_left(find::text("item 1")),
3017                Offset::new(0.0, 100.0)
3018            );
3019            assert_eq!(
3020                tester.get_top_left(find::text("item 3")),
3021                Offset::new(0.0, 300.0)
3022            );
3023            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4, 5, 6, 7]);
3024        });
3025    }
3026
3027    #[test]
3028    fn sliver_reorderable_list_items_inherit_default_text_style_icon_theme() {
3029        test_widgets(|tester| {
3030            let text_color = Color::new(0xffffffff);
3031            let icon_color = Color::new(0xff0000ff);
3032
3033            fn get_icon_style(tester: &WidgetTester) -> TextStyle {
3034                tester.widget(
3035                    find::descendant(find::by_type::<Icon>(), find::by_type::<RichText>()),
3036                    |rich_text: &RichText| rich_text.text.style().cloned().expect("a style"),
3037                )
3038            }
3039
3040            fn get_text_style(tester: &WidgetTester) -> TextStyle {
3041                tester.widget(
3042                    find::descendant(find::text("item 0"), find::by_type::<RichText>()),
3043                    |rich_text: &RichText| rich_text.text.style().cloned().expect("a style"),
3044                )
3045            }
3046
3047            fn color(style: TextStyle) -> Option<Color> {
3048                style.color.as_deref().copied()
3049            }
3050
3051            // This SliverReorderableList has just one item: "item 0".
3052            tester.pump_widget(test_list(
3053                &items(1),
3054                TestList {
3055                    text_color: Some(text_color),
3056                    icon_color: Some(icon_color),
3057                    ..TestList::default()
3058                },
3059            ));
3060            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3061            assert_eq!(color(get_icon_style(tester)), Some(icon_color));
3062            assert_eq!(color(get_text_style(tester)), Some(text_color));
3063
3064            // Dragging item 0 causes it to be reparented in the overlay. The item
3065            // should still inherit the IconTheme and DefaultTextStyle because they are
3066            // InheritedThemes.
3067            let at = tester.get_center(find::text("item 0"));
3068            let mut drag = start_gesture(tester, at);
3069            tester.pump_by(K_PRESS_TIMEOUT);
3070            tester.move_by(&mut drag, Offset::new(0.0, 50.0), true);
3071            tester.pump_by(K_PRESS_TIMEOUT);
3072            assert_eq!(
3073                tester.get_top_left(find::text("item 0")),
3074                Offset::new(0.0, 50.0)
3075            );
3076            assert_eq!(color(get_icon_style(tester)), Some(icon_color));
3077            assert_eq!(color(get_text_style(tester)), Some(text_color));
3078
3079            // Drag is complete, item 0 returns to where it was.
3080            tester.up(&drag);
3081            tester.pump_and_settle();
3082            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3083            assert_eq!(color(get_icon_style(tester)), Some(icon_color));
3084            assert_eq!(color(get_text_style(tester)), Some(text_color));
3085        });
3086    }
3087
3088    #[test]
3089    fn sliver_reorderable_list_custom_proxy_decorator() {
3090        test_widgets(|tester| {
3091            fn fade_transition_key() -> ValueKey<String> {
3092                ValueKey::new("reordered-fade".to_string())
3093            }
3094
3095            let proxy_decorator: ReorderItemProxyDecorator =
3096                Rc::new(|_app, child, _index, animation: AnimationRef<f64>| {
3097                    let listenable: Rc<dyn Listenable> = Rc::new(animation.clone());
3098                    AnimatedBuilder::new(listenable, move |app, _context, child| {
3099                        let fade_values = Tween::new(app, Some(1.0), Some(0.5));
3100                        let fade_animation = animation.drive(app, fade_values);
3101                        let mut fade =
3102                            FadeTransition::new(fade_animation).key(fade_transition_key().into());
3103                        if let Some(child) = child {
3104                            fade = fade.child(child.clone());
3105                        }
3106                        fade.into_widget()
3107                    })
3108                    .child(child)
3109                    .into_widget()
3110                });
3111            tester.pump_widget(test_list(
3112                &items(4),
3113                TestList {
3114                    proxy_decorator: Some(proxy_decorator),
3115                    ..TestList::default()
3116                },
3117            ));
3118
3119            let get_item_fade_transition = || find::by_key(fade_transition_key());
3120            let opacity = |tester: &WidgetTester| {
3121                let opacity = tester.widget(get_item_fade_transition(), |fade: &FadeTransition| {
3122                    fade.opacity.clone()
3123                });
3124                tester.update(|app| opacity.value(app))
3125            };
3126
3127            expect(tester, &get_item_fade_transition(), finds_nothing());
3128
3129            // Start gesture on first item
3130            let at = tester.get_center(find::text("item 0"));
3131            let mut drag = start_gesture(tester, at);
3132            tester.pump_by(K_PRESS_TIMEOUT);
3133
3134            // Drag enough for transition animation defined in proxyDecorator to start.
3135            tester.move_by(&mut drag, Offset::new(0.0, 50.0), true);
3136            tester.pump();
3137
3138            // At the start, opacity should be at 1.0.
3139            expect(tester, &get_item_fade_transition(), finds_one_widget());
3140            assert_eq!(opacity(tester), 1.0);
3141
3142            // Let animation run halfway.
3143            tester.pump_by(Duration::from_millis(125));
3144            let halfway = opacity(tester);
3145            assert!(halfway > 0.5);
3146            assert!(halfway < 1.0);
3147
3148            // Allow animation to run to the end.
3149            tester.pump_and_settle();
3150            expect(
3151                tester,
3152                &find::by_key(fade_transition_key()),
3153                finds_one_widget(),
3154            );
3155            assert_eq!(opacity(tester), 0.5);
3156
3157            // Finish reordering.
3158            tester.up(&drag);
3159            tester.pump_and_settle();
3160            expect(tester, &get_item_fade_transition(), finds_nothing());
3161        });
3162    }
3163
3164    #[test]
3165    fn reorderable_list_supports_items_with_nested_list_views_without_throwing_layout_exception() {
3166        test_widgets(|tester| {
3167            tester.pump_widget(
3168                TestWidgetsApp::new()
3169                    .home(
3170                        ReorderableList::new(
3171                            |_app, _context, index| {
3172                                ReorderableDragStartListener::new(
3173                                    Column::new().children([ListView::new()
3174                                        .shrink_wrap(true)
3175                                        .physics(Rc::new(ClampingScrollPhysics::new()))
3176                                        .children([
3177                                            Text::new("Other data").into_widget(),
3178                                            Text::new("Other data").into_widget(),
3179                                            Text::new("Other data").into_widget(),
3180                                        ])
3181                                        .into_widget()]),
3182                                    index,
3183                                )
3184                                .key(ValueKey::new(index).into())
3185                                .into_widget()
3186                            },
3187                            10,
3188                        )
3189                        .on_reorder_item(|_app, _from, _to| {}),
3190                    )
3191                    .builder(|app, context, child| {
3192                        // Ensure there is always a top padding to simulate a phone with
3193                        // safe area at the top. If the nested list doesn't have the
3194                        // padding removed before it is put into the overlay it will
3195                        // overflow the layout by the top padding.
3196                        MediaQuery::new(
3197                            MediaQuery::of(app, context)
3198                                .copy_with()
3199                                .padding(EdgeInsets::only(0.0, 50.0, 0.0, 0.0)),
3200                            child.expect("a child").clone(),
3201                        )
3202                        .into_widget()
3203                    }),
3204            );
3205
3206            // Start gesture on first item.
3207            let at = tester.get_center(find::by_key(ValueKey::new(0)));
3208            let mut drag = start_gesture(tester, at);
3209            tester.pump_by(K_PRESS_TIMEOUT);
3210
3211            // Drag enough for move to start.
3212            tester.move_by(&mut drag, Offset::new(0.0, 50.0), true);
3213            tester.pump_and_settle();
3214        });
3215    }
3216
3217    /// The drop-animation cases' `pressDragRelease`: settles before the release and pumps one
3218    /// frame after it.
3219    fn press_drag_release(tester: &mut WidgetTester, start: Offset, delta: Offset) {
3220        let mut drag = start_gesture(tester, start);
3221        tester.pump_by(K_PRESS_TIMEOUT);
3222        tester.move_by(&mut drag, delta, true);
3223        tester.pump_and_settle();
3224        tester.up(&drag);
3225        tester.pump();
3226    }
3227
3228    /// Dart's `pumpFor` of 'SliverReorderableList auto scrolls speed is configurable': a frame
3229    /// now, then a frame each `interval` plus a millisecond until `duration` has passed.
3230    fn pump_for(tester: &mut WidgetTester, duration: Duration, interval: Duration) {
3231        tester.pump();
3232        let mut times = duration.as_millis().div_ceil(interval.as_millis());
3233        while times > 0 {
3234            tester.pump_by(interval + Duration::from_millis(1));
3235            times -= 1;
3236        }
3237    }
3238
3239    #[test]
3240    fn sliver_reorderable_list_auto_scroll_speed_is_configurable() {
3241        test_widgets(|tester| {
3242            fn pump_list_and_drag(
3243                tester: &mut WidgetTester,
3244                auto_scroller_velocity_scalar: f64,
3245            ) -> f64 {
3246                let items = items(10);
3247                let controller: ScrollControllerRef = ScrollController::new(
3248                    &mut tester.cell.borrow_mut(),
3249                    0.0,
3250                    true,
3251                    None,
3252                    None,
3253                    None,
3254                )
3255                .erase();
3256                let builder_items = Rc::clone(&items);
3257                tester.pump_widget(
3258                    TestWidgetsApp::new().home(
3259                        CustomScrollView::new()
3260                            .controller(controller.clone())
3261                            .slivers([SliverReorderableList::new(
3262                                move |_app, _context, index| {
3263                                    let item = builder_items.borrow()[index as usize];
3264                                    Container::new()
3265                                        .key(ValueKey::new(item).into())
3266                                        .height(100.0)
3267                                        .color(if item % 2 == 1 {
3268                                            K_RED_COLOR
3269                                        } else {
3270                                            K_GREEN_COLOR
3271                                        })
3272                                        .child(
3273                                            ReorderableDragStartListener::new(
3274                                                Row::new()
3275                                                    .cross_axis_alignment(CrossAxisAlignment::Start)
3276                                                    .children([
3277                                                        Text::new(format!("item {item}"))
3278                                                            .into_widget(),
3279                                                        Icon::new(Some(k_drag_handle_icon_data()))
3280                                                            .into_widget(),
3281                                                    ]),
3282                                                index,
3283                                            )
3284                                            .into_widget(),
3285                                        )
3286                                        .into_widget()
3287                                },
3288                                items.borrow().len() as i32,
3289                            )
3290                            .on_reorder_item(|_app, _from, _to| {})
3291                            .auto_scroller_velocity_scalar(auto_scroller_velocity_scalar)
3292                            .into_widget()]),
3293                    ),
3294                );
3295
3296                assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
3297
3298                let item = find::text("item 0");
3299                let mut drag = start_gesture(tester, tester.get_center(item));
3300
3301                // Drag just enough to touch the edge but not surpass it, so the auto scroller
3302                // is not yet triggered.
3303                tester.move_by(&mut drag, Offset::new(0.0, 500.0), true);
3304                pump_for(
3305                    tester,
3306                    Duration::from_millis(200),
3307                    Duration::from_millis(50),
3308                );
3309
3310                assert_eq!(controller.offset(&tester.cell.borrow()), 0.0);
3311
3312                // Now drag a little bit more so the auto scroller triggers.
3313                tester.move_by(&mut drag, Offset::new(0.0, 50.0), true);
3314                pump_for(
3315                    tester,
3316                    Duration::from_millis(600),
3317                    Duration::from_millis((1000.0 / auto_scroller_velocity_scalar).round() as u64),
3318                );
3319
3320                controller.offset(&tester.cell.borrow())
3321            }
3322
3323            const FAST_VELOCITY_SCALAR: f64 = 20.0;
3324            let offset_for_fast_scroller = pump_list_and_drag(tester, FAST_VELOCITY_SCALAR);
3325
3326            // Reset widget tree
3327            tester.pump_widget(SizedBox::new());
3328
3329            const SLOW_VELOCITY_SCALAR: f64 = 5.0;
3330            let offset_for_slow_scroller = pump_list_and_drag(tester, SLOW_VELOCITY_SCALAR);
3331
3332            assert_eq!(
3333                offset_for_fast_scroller / offset_for_slow_scroller,
3334                FAST_VELOCITY_SCALAR / SLOW_VELOCITY_SCALAR
3335            );
3336        });
3337    }
3338
3339    #[test]
3340    fn sliver_reorderable_list_properly_animates_the_drop_in_a_reversed_list() {
3341        test_widgets(|tester| {
3342            // Regression test for https://github.com/flutter/flutter/issues/110949
3343            let items = items(8);
3344
3345            // The TestList is 800x600 SliverReorderableList with 8 items 800x100 each.
3346            // Each item has a text widget with 'item $index' that can be moved by a
3347            // press and drag gesture. For this test we are reversing the order so
3348            // the first item is at the bottom.
3349            tester.pump_widget(test_list(
3350                &items,
3351                TestList {
3352                    reverse: true,
3353                    ..TestList::default()
3354                },
3355            ));
3356
3357            assert_eq!(
3358                tester.get_top_left(find::text("item 0")),
3359                Offset::new(0.0, 500.0)
3360            );
3361            assert_eq!(
3362                tester.get_top_left(find::text("item 2")),
3363                Offset::new(0.0, 300.0)
3364            );
3365
3366            // Drag item 0 up and insert it between item 1 and item 2. It should
3367            // smoothly animate.
3368            let start = tester.get_center(find::text("item 0"));
3369            press_drag_release(tester, start, Offset::new(0.0, -50.0));
3370            assert_eq!(
3371                tester.get_top_left(find::text("item 0")),
3372                Offset::new(0.0, 450.0)
3373            );
3374            assert_eq!(
3375                tester.get_top_left(find::text("item 1")),
3376                Offset::new(0.0, 500.0)
3377            );
3378            assert_eq!(
3379                tester.get_top_left(find::text("item 2")),
3380                Offset::new(0.0, 300.0)
3381            );
3382
3383            // After the first several frames we should be moving closer to the final position,
3384            // not further away as was the case with the original bug.
3385            tester.pump_by(Duration::from_millis(10));
3386            let dy = tester.get_top_left(find::text("item 0")).dy();
3387            assert!(dy < 450.0);
3388            assert!(dy > 400.0);
3389
3390            // Sample the middle (don't use exact values as it depends on the internal
3391            // curve being used).
3392            tester.pump_by(Duration::from_millis(125));
3393            let dy = tester.get_top_left(find::text("item 0")).dy();
3394            assert!(dy < 450.0);
3395            assert!(dy > 400.0);
3396
3397            // Sample the end of the animation.
3398            tester.pump_by(Duration::from_millis(100));
3399            let dy = tester.get_top_left(find::text("item 0")).dy();
3400            assert!(dy < 450.0);
3401            assert!(dy > 400.0);
3402
3403            // Wait for it to finish, it should be back to the original position
3404            tester.pump_and_settle();
3405            assert_eq!(
3406                tester.get_top_left(find::text("item 0")),
3407                Offset::new(0.0, 400.0)
3408            );
3409        });
3410    }
3411
3412    #[test]
3413    fn sliver_reorderable_list_properly_animates_the_drop_at_starting_position_in_a_reversed_list()
3414    {
3415        test_widgets(|tester| {
3416            // Regression test for https://github.com/flutter/flutter/issues/84625
3417            let items = items(8);
3418
3419            // The TestList is 800x600 SliverReorderableList with 8 items 800x100 each.
3420            // Each item has a text widget with 'item $index' that can be moved by a
3421            // press and drag gesture. For this test we are reversing the order so
3422            // the first item is at the bottom.
3423            tester.pump_widget(test_list(
3424                &items,
3425                TestList {
3426                    reverse: true,
3427                    ..TestList::default()
3428                },
3429            ));
3430
3431            assert_eq!(
3432                tester.get_top_left(find::text("item 0")),
3433                Offset::new(0.0, 500.0)
3434            );
3435            assert_eq!(
3436                tester.get_top_left(find::text("item 1")),
3437                Offset::new(0.0, 400.0)
3438            );
3439
3440            // Drag item 0 downwards off the edge and let it snap back. It should
3441            // smoothly animate back up.
3442            let start = tester.get_center(find::text("item 0"));
3443            press_drag_release(tester, start, Offset::new(0.0, 50.0));
3444            assert_eq!(
3445                tester.get_top_left(find::text("item 0")),
3446                Offset::new(0.0, 550.0)
3447            );
3448            assert_eq!(
3449                tester.get_top_left(find::text("item 1")),
3450                Offset::new(0.0, 400.0)
3451            );
3452
3453            // After the first several frames we should be moving closer to the final position,
3454            // not further away as was the case with the original bug.
3455            tester.pump_by(Duration::from_millis(10));
3456            assert!(tester.get_top_left(find::text("item 0")).dy() < 550.0);
3457
3458            // Sample the middle (don't use exact values as it depends on the internal
3459            // curve being used).
3460            tester.pump_by(Duration::from_millis(125));
3461            assert!(tester.get_top_left(find::text("item 0")).dy() < 550.0);
3462
3463            // Wait for it to finish, it should be back to the original position
3464            tester.pump_and_settle();
3465            assert_eq!(
3466                tester.get_top_left(find::text("item 0")),
3467                Offset::new(0.0, 500.0)
3468            );
3469        });
3470    }
3471
3472    /// The starting-position cases: drag `item` down 100, settle, then back by `back`, and let
3473    /// go; answers the item's top after 200ms of the drop.
3474    fn drag_down_then_back(tester: &mut WidgetTester, item: &str, back: f64) -> (Offset, Offset) {
3475        let at = tester.get_center(find::text(item));
3476        let mut drag = start_gesture(tester, at);
3477        tester.pump_by(K_PRESS_TIMEOUT);
3478        tester.move_by(&mut drag, Offset::new(0.0, 100.0), true);
3479        tester.pump_and_settle();
3480        tester.move_by(&mut drag, Offset::new(0.0, back), true);
3481        tester.pump();
3482        let dragged = tester.get_top_left(find::text(item));
3483        let item_1 = tester.get_top_left(find::text("item 1"));
3484        let released = (dragged, item_1);
3485
3486        // Now leave the drag.
3487        tester.up(&drag);
3488        tester.pump();
3489        released
3490    }
3491
3492    #[test]
3493    fn sliver_reorderable_list_properly_animates_the_drop_at_starting_position() {
3494        test_widgets(|tester| {
3495            // Regression test for https://github.com/flutter/flutter/issues/150843
3496            // This tests the overshoot case where an item is dragged back 110% of the way
3497            let items = items(3);
3498
3499            // The TestList is 300x100 SliverReorderableList with 3 items 100x100 each.
3500            // Each item has a text widget with 'item $index' that can be moved by a
3501            // press and drag gesture. For this test the first item is at the top
3502            tester.pump_widget(test_list(&items, TestList::default()));
3503
3504            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3505            assert_eq!(
3506                tester.get_top_left(find::text("item 1")),
3507                Offset::new(0.0, 100.0)
3508            );
3509
3510            // Drag item 0 downwards and then upwards.
3511            let (item_0, item_1) = drag_down_then_back(tester, "item 0", -110.0);
3512            assert_eq!(item_0, Offset::new(0.0, -10.0));
3513            assert_eq!(item_1, Offset::new(0.0, 100.0));
3514
3515            // It should not go to index 1 and come back
3516            tester.pump_by(Duration::from_millis(200));
3517            assert!(tester.get_top_left(find::text("item 0")).dy() < 50.0);
3518        });
3519    }
3520
3521    #[test]
3522    fn sliver_reorderable_list_properly_animates_the_drop_at_starting_position_with_reverse_true() {
3523        test_widgets(|tester| {
3524            // Regression test for https://github.com/flutter/flutter/issues/150843
3525            // This tests the overshoot case where an item is dragged back 110% of the way in a
3526            // reverse list
3527            let items = items(3);
3528
3529            // The TestList is 300x100 SliverReorderableList with 3 items 100x100 each.
3530            // Each item has a text widget with 'item $index' that can be moved by a
3531            // press and drag gesture. For this test the first item is at the top
3532            tester.pump_widget(test_list(
3533                &items,
3534                TestList {
3535                    reverse: true,
3536                    ..TestList::default()
3537                },
3538            ));
3539
3540            assert_eq!(
3541                tester.get_top_left(find::text("item 2")),
3542                Offset::new(0.0, 300.0)
3543            );
3544            assert_eq!(
3545                tester.get_top_left(find::text("item 1")),
3546                Offset::new(0.0, 400.0)
3547            );
3548
3549            // Drag item 2 downwards and then upwards.
3550            let (item_2, item_1) = drag_down_then_back(tester, "item 2", -110.0);
3551            assert_eq!(item_2, Offset::new(0.0, 290.0));
3552            assert_eq!(item_1, Offset::new(0.0, 300.0));
3553
3554            // It should not go to index 0 and come back
3555            tester.pump_by(Duration::from_millis(200));
3556            assert!(tester.get_top_left(find::text("item 2")).dy() > 350.0);
3557        });
3558    }
3559
3560    #[test]
3561    fn sliver_reorderable_list_properly_animates_the_drop_at_starting_position_undershoot() {
3562        test_widgets(|tester| {
3563            // Regression test for https://github.com/flutter/flutter/issues/88331
3564            // This tests the edge case where an item is dragged back only 90% of the way
3565            let items = items(3);
3566
3567            // The TestList is 300x100 SliverReorderableList with 3 items 100x100 each.
3568            // Each item has a text widget with 'item $index' that can be moved by a
3569            // press and drag gesture. For this test the first item is at the top
3570            tester.pump_widget(test_list(&items, TestList::default()));
3571
3572            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3573            assert_eq!(
3574                tester.get_top_left(find::text("item 1")),
3575                Offset::new(0.0, 100.0)
3576            );
3577
3578            // Drag item 0 downwards and then upwards (but not all the way back).
3579            let (item_0, item_1) = drag_down_then_back(tester, "item 0", -90.0);
3580            assert_eq!(item_0, Offset::new(0.0, 10.0));
3581            assert_eq!(item_1, Offset::new(0.0, 100.0));
3582
3583            // It should animate back to the original position
3584            tester.pump_by(Duration::from_millis(200));
3585            assert!(tester.get_top_left(find::text("item 0")).dy() < 10.0);
3586        });
3587    }
3588
3589    #[test]
3590    fn sliver_reorderable_list_properly_animates_the_drop_at_starting_position_with_reverse_true_undershoot()
3591     {
3592        test_widgets(|tester| {
3593            // Regression test for https://github.com/flutter/flutter/issues/88331
3594            // This tests the edge case where an item is dragged back only 90% of the way in a
3595            // reverse list
3596            let items = items(3);
3597
3598            // The TestList is 300x100 SliverReorderableList with 3 items 100x100 each.
3599            // Each item has a text widget with 'item $index' that can be moved by a
3600            // press and drag gesture. For this test the first item is at the top
3601            tester.pump_widget(test_list(
3602                &items,
3603                TestList {
3604                    reverse: true,
3605                    ..TestList::default()
3606                },
3607            ));
3608
3609            assert_eq!(
3610                tester.get_top_left(find::text("item 2")),
3611                Offset::new(0.0, 300.0)
3612            );
3613            assert_eq!(
3614                tester.get_top_left(find::text("item 1")),
3615                Offset::new(0.0, 400.0)
3616            );
3617
3618            // Drag item 2 downwards and then upwards (but not all the way back).
3619            let (item_2, item_1) = drag_down_then_back(tester, "item 2", -90.0);
3620            assert_eq!(item_2, Offset::new(0.0, 310.0));
3621            assert_eq!(item_1, Offset::new(0.0, 300.0));
3622
3623            // It should animate back to the original position
3624            tester.pump_by(Duration::from_millis(200));
3625            let dy = tester.get_top_left(find::text("item 2")).dy();
3626            assert!((dy - 300.0).abs() <= 10.0, "{dy} is not within 10 of 300");
3627        });
3628    }
3629
3630    #[test]
3631    fn reorderable_list_animation_jumping_on_interruption() {
3632        test_widgets(|tester| {
3633            // Regression test for https://github.com/flutter/flutter/issues/173243
3634            let items = items(3);
3635
3636            tester.pump_widget(test_list(&items, TestList::default()));
3637            tester.pump_and_settle();
3638
3639            assert_eq!(tester.get_top_left(find::text("item 0")), Offset::ZERO);
3640            assert_eq!(
3641                tester.get_top_left(find::text("item 1")),
3642                Offset::new(0.0, 100.0)
3643            );
3644
3645            let at = tester.get_center(find::text("item 0"));
3646            let mut drag = start_gesture(tester, at);
3647            tester.pump_by(K_PRESS_TIMEOUT);
3648
3649            // Drag item 0 down past the swap threshold at 50px.
3650            for _ in 0..6 {
3651                tester.move_by(&mut drag, Offset::new(0.0, 10.0), true);
3652                tester.pump_by(Duration::from_millis(50));
3653            }
3654
3655            let item_1_y_before_interrupt = tester.get_center(find::text("item 1")).dy();
3656
3657            // Drag back to trigger swap reversal.
3658            tester.move_by(&mut drag, Offset::new(0.0, -10.0), true);
3659            tester.pump_by(Duration::from_millis(50));
3660
3661            let item_1_y_after_interrupt = tester.get_center(find::text("item 1")).dy();
3662
3663            // Position should not jump when animation is interrupted.
3664            assert!(
3665                (item_1_y_after_interrupt - item_1_y_before_interrupt).abs() <= 5.0,
3666                "Animation jumping detected! Position changed from {item_1_y_before_interrupt} \
3667                 to {item_1_y_after_interrupt}"
3668            );
3669
3670            for _ in 0..5 {
3671                tester.move_by(&mut drag, Offset::new(0.0, -10.0), true);
3672                tester.pump_by(Duration::from_millis(50));
3673            }
3674
3675            tester.up(&drag);
3676            tester.pump_and_settle();
3677        });
3678    }
3679
3680    /// The start and end cases' two drags of `item 0`: from index 0 to 3, then from 2 to 0,
3681    /// each started after `press`; checks the reported indices.
3682    fn check_reorder_start_and_end(
3683        tester: &mut WidgetTester,
3684        press: Duration,
3685        start_index: &Rc<Cell<Option<i32>>>,
3686        end_index: &Rc<Cell<Option<i32>>>,
3687    ) {
3688        let item_0 = || find::text_containing("item 0");
3689
3690        let at = tester.get_center(item_0());
3691        let mut drag = start_gesture(tester, at);
3692        tester.pump_by(press);
3693        // Drag enough for move to start.
3694        tester.move_by(&mut drag, Offset::new(0.0, 20.0), true);
3695
3696        assert_eq!(start_index.get(), Some(0));
3697        assert_eq!(end_index.get(), None);
3698
3699        // Move item0 from index 0 to index 3
3700        tester.move_by(&mut drag, Offset::new(0.0, 300.0), true);
3701        tester.pump_and_settle();
3702        tester.up(&drag);
3703        tester.pump_and_settle();
3704
3705        assert_eq!(end_index.get(), Some(3));
3706
3707        start_index.set(None);
3708        end_index.set(None);
3709
3710        let at = tester.get_center(item_0());
3711        let mut drag = start_gesture(tester, at);
3712        tester.pump_by(press);
3713        // Drag enough for move to start.
3714        tester.move_by(&mut drag, Offset::new(0.0, 20.0), true);
3715
3716        assert_eq!(start_index.get(), Some(2));
3717        assert_eq!(end_index.get(), None);
3718
3719        // Move item0 from index 2 to index 0
3720        tester.move_by(&mut drag, Offset::new(0.0, -200.0), true);
3721        tester.pump_and_settle();
3722        tester.up(&drag);
3723        tester.pump_and_settle();
3724
3725        assert_eq!(end_index.get(), Some(0));
3726    }
3727
3728    /// An `onReorderStart` or `onReorderEnd` that records its index.
3729    fn record_index(index: &Rc<Cell<Option<i32>>>) -> ReorderIndexCallback {
3730        let index = Rc::clone(index);
3731        Rc::new(move |_app, value| index.set(Some(value)))
3732    }
3733
3734    #[test]
3735    fn sliver_reorderable_list_calls_on_reorder_start_and_on_reorder_end_correctly() {
3736        test_widgets(|tester| {
3737            let items = items(8);
3738            let start_index = Rc::new(Cell::new(None));
3739            let end_index = Rc::new(Cell::new(None));
3740
3741            tester.pump_widget(test_list(
3742                &items,
3743                TestList {
3744                    on_reorder_start: Some(record_index(&start_index)),
3745                    on_reorder_end: Some(record_index(&end_index)),
3746                    ..TestList::default()
3747                },
3748            ));
3749
3750            check_reorder_start_and_end(tester, K_PRESS_TIMEOUT, &start_index, &end_index);
3751        });
3752    }
3753
3754    #[test]
3755    fn reorderable_list_calls_on_reorder_start_and_on_reorder_end_correctly() {
3756        test_widgets(|tester| {
3757            let items = items(8);
3758            let start_index = Rc::new(Cell::new(None));
3759            let end_index = Rc::new(Cell::new(None));
3760            let calls = Rc::new(Cell::new(0));
3761
3762            let mut list = ReorderableList::new(sized_item(&items, true, true), 8)
3763                .on_reorder_item(handle_reorder(&items, &calls));
3764            list.on_reorder_start = Some(record_index(&start_index));
3765            list.on_reorder_end = Some(record_index(&end_index));
3766            tester.pump_widget(TestWidgetsApp::new().home(list));
3767
3768            check_reorder_start_and_end(tester, K_LONG_PRESS_TIMEOUT, &start_index, &end_index);
3769        });
3770    }
3771
3772    /// The callback cases' two drags of `item 0`: down by 50, then back up by 50.
3773    fn drag_item_0_down_then_up(tester: &mut WidgetTester, after_first: impl FnOnce()) {
3774        // Start gesture on the first item.
3775        let at = tester.get_center(find::text("item 0"));
3776        let mut drag_down = start_gesture(tester, at);
3777        tester.pump_by(K_PRESS_TIMEOUT);
3778
3779        // Drag enough to move down the first item.
3780        tester.move_by(&mut drag_down, Offset::new(0.0, 50.0), true);
3781        tester.pump();
3782        tester.up(&drag_down);
3783        tester.pump_and_settle();
3784
3785        after_first();
3786
3787        // Now do the reverse.
3788        let at = tester.get_center(find::text("item 0"));
3789        let mut drag_up = start_gesture(tester, at);
3790        tester.pump_by(K_PRESS_TIMEOUT);
3791
3792        // Drag enough to move up the first item.
3793        tester.move_by(&mut drag_up, Offset::new(0.0, -50.0), true);
3794        tester.pump();
3795        tester.up(&drag_up);
3796        tester.pump_and_settle();
3797    }
3798
3799    /// The old `onReorder` of the callback cases, which adjusts `toIndex` itself.
3800    fn handle_old_reorder(
3801        items: &Items,
3802        calls: &Rc<Cell<i32>>,
3803    ) -> impl Fn(&mut App, i32, i32) + 'static {
3804        let items = Rc::clone(items);
3805        let calls = Rc::clone(calls);
3806        move |_app, from_index, mut to_index| {
3807            calls.set(calls.get() + 1);
3808
3809            if from_index < to_index {
3810                to_index -= 1;
3811            }
3812
3813            let mut items = items.borrow_mut();
3814            let item = items.remove(from_index as usize);
3815            items.insert(to_index as usize, item);
3816        }
3817    }
3818
3819    #[test]
3820    #[expect(deprecated, reason = "Dart's case exercises the deprecated onReorder")]
3821    fn sliver_reorderable_list_calls_old_on_reorder_callback_correctly() {
3822        test_widgets(|tester| {
3823            let on_reorder_call_count = Rc::new(Cell::new(0));
3824            let items = items(5);
3825
3826            tester.pump_widget(
3827                TestWidgetsApp::new().home(
3828                    CustomScrollView::new().slivers([SliverReorderableList::new(
3829                        sized_item(&items, false, true),
3830                        5,
3831                    )
3832                    .on_reorder(handle_old_reorder(&items, &on_reorder_call_count))
3833                    .into_widget()]),
3834                ),
3835            );
3836
3837            drag_item_0_down_then_up(tester, || {
3838                assert_eq!(on_reorder_call_count.get(), 1);
3839                assert_eq!(*items.borrow(), vec![1, 0, 2, 3, 4]);
3840            });
3841
3842            assert_eq!(on_reorder_call_count.get(), 2);
3843            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4]);
3844        });
3845    }
3846
3847    #[test]
3848    fn sliver_reorderable_list_calls_on_reorder_item_callback_correctly() {
3849        test_widgets(|tester| {
3850            let calls = Rc::new(Cell::new(0));
3851            let items = items(5);
3852
3853            tester.pump_widget(
3854                TestWidgetsApp::new().home(
3855                    CustomScrollView::new().slivers([SliverReorderableList::new(
3856                        sized_item(&items, false, true),
3857                        5,
3858                    )
3859                    .on_reorder_item(handle_reorder(&items, &calls))
3860                    .into_widget()]),
3861                ),
3862            );
3863
3864            drag_item_0_down_then_up(tester, || {
3865                assert_eq!(*items.borrow(), vec![1, 0, 2, 3, 4]);
3866            });
3867
3868            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4]);
3869        });
3870    }
3871
3872    #[test]
3873    #[should_panic(expected = "The onReorder callback is obsolete")]
3874    fn sliver_reorderable_list_asserts_if_neither_on_reorder_and_on_reorder_item_are_provided() {
3875        let _ =
3876            SliverReorderableList::new(|_app, _context, _index| SizedBox::new().into_widget(), 0)
3877                .into_widget();
3878    }
3879
3880    #[test]
3881    #[should_panic(expected = "The onReorder callback is obsolete")]
3882    #[expect(deprecated, reason = "Dart's case passes the deprecated onReorder")]
3883    fn sliver_reorderable_list_asserts_if_both_on_reorder_and_on_reorder_item_are_provided() {
3884        let _ =
3885            SliverReorderableList::new(|_app, _context, _index| SizedBox::new().into_widget(), 0)
3886                .on_reorder(|_app, _from, _to| {})
3887                .on_reorder_item(|_app, _from, _to| {})
3888                .into_widget();
3889    }
3890
3891    #[test]
3892    #[expect(deprecated, reason = "Dart's case exercises the deprecated onReorder")]
3893    fn reorderable_list_calls_old_on_reorder_callback_correctly() {
3894        test_widgets(|tester| {
3895            let on_reorder_call_count = Rc::new(Cell::new(0));
3896            let items = items(5);
3897
3898            tester.pump_widget(
3899                TestWidgetsApp::new().home(
3900                    ReorderableList::new(sized_item(&items, false, true), 5)
3901                        .on_reorder(handle_old_reorder(&items, &on_reorder_call_count)),
3902                ),
3903            );
3904
3905            drag_item_0_down_then_up(tester, || {
3906                assert_eq!(on_reorder_call_count.get(), 1);
3907                assert_eq!(*items.borrow(), vec![1, 0, 2, 3, 4]);
3908            });
3909
3910            assert_eq!(on_reorder_call_count.get(), 2);
3911            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4]);
3912        });
3913    }
3914
3915    #[test]
3916    fn reorderable_list_calls_on_reorder_item_callback_correctly() {
3917        test_widgets(|tester| {
3918            let calls = Rc::new(Cell::new(0));
3919            let items = items(5);
3920
3921            tester.pump_widget(
3922                TestWidgetsApp::new().home(
3923                    ReorderableList::new(sized_item(&items, false, true), 5)
3924                        .on_reorder_item(handle_reorder(&items, &calls)),
3925                ),
3926            );
3927
3928            drag_item_0_down_then_up(tester, || {
3929                assert_eq!(*items.borrow(), vec![1, 0, 2, 3, 4]);
3930            });
3931
3932            assert_eq!(*items.borrow(), vec![0, 1, 2, 3, 4]);
3933        });
3934    }
3935
3936    #[test]
3937    #[should_panic(expected = "The onReorder callback is obsolete")]
3938    fn reorderable_list_asserts_if_neither_on_reorder_and_on_reorder_item_are_provided() {
3939        let _ = ReorderableList::new(|_app, _context, _index| SizedBox::new().into_widget(), 0)
3940            .into_widget();
3941    }
3942
3943    #[test]
3944    #[should_panic(expected = "The onReorder callback is obsolete")]
3945    #[expect(deprecated, reason = "Dart's case passes the deprecated onReorder")]
3946    fn reorderable_list_asserts_if_both_on_reorder_and_on_reorder_item_are_provided() {
3947        let _ = ReorderableList::new(|_app, _context, _index| SizedBox::new().into_widget(), 0)
3948            .on_reorder(|_app, _from, _to| {})
3949            .on_reorder_item(|_app, _from, _to| {})
3950            .into_widget();
3951    }
3952
3953    /// The extent cases' items: `SizedBox(key: ValueKey(numbers[index]), height: 20 +
3954    /// numbers[index] * 10)` over a drag listener of `Text('${numbers[index]}')`.
3955    fn number_item(numbers: &Items) -> impl Fn(&mut App, BuildContext, i32) -> WidgetRef + 'static {
3956        let numbers = Rc::clone(numbers);
3957        move |_app, _context, index| {
3958            let number = numbers.borrow()[index as usize];
3959            SizedBox::new()
3960                .key(ValueKey::new(number).into())
3961                .height(f64::from(20 + number * 10))
3962                .child(ReorderableDragStartListener::new(
3963                    Text::new(number.to_string()),
3964                    index,
3965                ))
3966                .into_widget()
3967        }
3968    }
3969
3970    #[test]
3971    #[should_panic(
3972        expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
3973    )]
3974    fn reorderable_list_asserts_on_both_non_null_item_extent_and_prototype_item() {
3975        let numbers = Rc::new(RefCell::new(vec![0, 1, 2]));
3976        let _ = ReorderableList::new(number_item(&numbers), 3)
3977            .item_extent(30.0)
3978            .prototype_item(SizedBox::new())
3979            .on_reorder_item(|_app, _from, _to| {})
3980            .into_widget();
3981    }
3982
3983    #[test]
3984    fn reorderable_list_passes_item_extent_builder_to_sliver_reorderable_list() {
3985        test_widgets(|tester| {
3986            // Regression test for https://github.com/flutter/flutter/issues/155936
3987            let item_count = 5;
3988            let items: Rc<Vec<f64>> = Rc::new(vec![10.0, 20.0, 30.0, 40.0, 50.0]);
3989
3990            // The list has five elements, that indicate the extent for the item at the given
3991            // index.
3992            let builder_items = Rc::clone(&items);
3993            let extent_items = Rc::clone(&items);
3994            tester.pump_widget(
3995                TestWidgetsApp::new().home(
3996                    ReorderableList::new(
3997                        move |_app, _context, index| {
3998                            // Dart's `ValueKey<double>`: a double's bits, as `f64` has no `Hash`.
3999                            SizedBox::new()
4000                                .key(ValueKey::new(builder_items[index as usize].to_bits()).into())
4001                                .child(Text::new(format!("Item {index}")))
4002                                .into_widget()
4003                        },
4004                        item_count,
4005                    )
4006                    .on_reorder_item(|_app, _from, _to| {})
4007                    .item_extent_builder(Rc::new(move |index, _dimensions| {
4008                        Some(extent_items[index as usize])
4009                    })),
4010                ),
4011            );
4012
4013            let expected_extents: HashMap<i32, f64> =
4014                HashMap::from([(0, 10.0), (1, 20.0), (2, 30.0), (3, 40.0), (4, 50.0)]);
4015
4016            let item_extents: HashMap<i32, f64> = (0..item_count)
4017                .map(|i| {
4018                    (
4019                        i,
4020                        tester.get_size(find::text(&format!("Item {i}"))).height(),
4021                    )
4022                })
4023                .collect();
4024
4025            assert_eq!(item_extents, expected_extents);
4026        });
4027    }
4028
4029    #[test]
4030    #[should_panic(
4031        expected = "You can only pass one of itemExtent, prototypeItem and itemExtentBuilder."
4032    )]
4033    fn sliver_reorderable_list_asserts_on_both_non_null_item_extent_and_prototype_item() {
4034        let numbers = Rc::new(RefCell::new(vec![0, 1, 2]));
4035        let _ = SliverReorderableList::new(number_item(&numbers), 3)
4036            .item_extent(30.0)
4037            .prototype_item(SizedBox::new())
4038            .on_reorder_item(|_app, _from, _to| {})
4039            .into_widget();
4040    }
4041
4042    /// The height of each of the extent cases' three items: Dart's
4043    /// `tester.getSize(find.text('$i').hitTestable()).height`, the one `Text` each shows.
4044    fn number_heights(tester: &WidgetTester) -> [f64; 3] {
4045        [0, 1, 2].map(|i| tester.get_size(find::text(&i.to_string())).height())
4046    }
4047
4048    #[test]
4049    fn if_item_extent_is_non_null_children_have_same_extent_in_the_scroll_direction() {
4050        test_widgets(|tester| {
4051            let numbers = Rc::new(RefCell::new(vec![0, 1, 2]));
4052
4053            let reorder_numbers = Rc::clone(&numbers);
4054            let builder_numbers = Rc::clone(&numbers);
4055            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
4056                move |_app, _context, _set_state| {
4057                    let reorder_numbers = Rc::clone(&reorder_numbers);
4058                    ReorderableList::new(number_item(&builder_numbers), 3)
4059                        .item_extent(30.0)
4060                        .on_reorder_item(move |_app, from_index, to_index| {
4061                            let mut numbers = reorder_numbers.borrow_mut();
4062                            let value = numbers.remove(from_index as usize);
4063                            numbers.insert(to_index as usize, value);
4064                        })
4065                        .into_widget()
4066                },
4067            )));
4068
4069            assert_eq!(number_heights(tester), [30.0, 30.0, 30.0]);
4070        });
4071    }
4072
4073    #[test]
4074    fn if_prototype_item_is_non_null_children_have_same_extent_in_the_scroll_direction() {
4075        test_widgets(|tester| {
4076            let numbers = Rc::new(RefCell::new(vec![0, 1, 2]));
4077
4078            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
4079                move |_app, _context, _set_state| {
4080                    ReorderableList::new(number_item(&numbers), 3)
4081                        .prototype_item(SizedBox::new().height(30.0).child(Text::new("3")))
4082                        .on_reorder_item(|_app, _from, _to| {})
4083                        .into_widget()
4084                },
4085            )));
4086
4087            assert_eq!(number_heights(tester), [30.0, 30.0, 30.0]);
4088        });
4089    }
4090
4091    /// The listener cases: drag `item 0` down by 50 after `press`, with the listener kind and
4092    /// `enabled` given; answers the reorder calls and the items.
4093    fn drag_with_listener(
4094        tester: &mut WidgetTester,
4095        delayed: bool,
4096        enabled: bool,
4097        press: Duration,
4098        settle_first: bool,
4099    ) -> (i32, Vec<i32>) {
4100        let on_reorder_call_count = Rc::new(Cell::new(0));
4101        let items = items(5);
4102
4103        // The list has five elements of height 100
4104        tester.pump_widget(
4105            TestWidgetsApp::new().home(
4106                ReorderableList::new(sized_item(&items, delayed, enabled), 5)
4107                    .on_reorder_item(handle_reorder(&items, &on_reorder_call_count)),
4108            ),
4109        );
4110        if settle_first {
4111            tester.pump_and_settle();
4112        }
4113
4114        // Start gesture on first item
4115        let at = tester.get_center(find::text("item 0"));
4116        let mut drag = start_gesture(tester, at);
4117        tester.pump_by(press);
4118
4119        // Drag enough to move down the first item
4120        tester.move_by(&mut drag, Offset::new(0.0, 50.0), true);
4121        tester.pump();
4122        tester.up(&drag);
4123        tester.pump_and_settle();
4124
4125        let items = items.borrow().clone();
4126        (on_reorder_call_count.get(), items)
4127    }
4128
4129    #[test]
4130    fn reorderable_drag_start_listener_it_should_allow_the_item_to_be_dragged_when_enabled_is_true()
4131    {
4132        test_widgets(|tester| {
4133            let (calls, items) = drag_with_listener(tester, false, true, K_PRESS_TIMEOUT, false);
4134            assert_eq!(calls, 1);
4135            assert_eq!(items, vec![1, 0, 2, 3, 4]);
4136        });
4137    }
4138
4139    #[test]
4140    fn reorderable_drag_start_listener_it_should_not_allow_the_item_to_be_dragged_when_enabled_is_false()
4141     {
4142        test_widgets(|tester| {
4143            let (calls, items) =
4144                drag_with_listener(tester, false, false, K_LONG_PRESS_TIMEOUT, false);
4145            assert_eq!(calls, 0);
4146            assert_eq!(items, vec![0, 1, 2, 3, 4]);
4147        });
4148    }
4149
4150    #[test]
4151    fn reorderable_delayed_drag_start_listener_it_should_allow_the_item_to_be_dragged_when_enabled_is_true()
4152     {
4153        test_widgets(|tester| {
4154            let (calls, items) = drag_with_listener(tester, true, true, K_LONG_PRESS_TIMEOUT, true);
4155            assert_eq!(calls, 1);
4156            assert_eq!(items, vec![1, 0, 2, 3, 4]);
4157        });
4158    }
4159
4160    #[test]
4161    fn reorderable_delayed_drag_start_listener_it_should_not_allow_the_item_to_be_dragged_when_enabled_is_false()
4162     {
4163        test_widgets(|tester| {
4164            let (calls, items) =
4165                drag_with_listener(tester, true, false, K_LONG_PRESS_TIMEOUT, false);
4166            assert_eq!(calls, 0);
4167            assert_eq!(items, vec![0, 1, 2, 3, 4]);
4168        });
4169    }
4170
4171    #[test]
4172    fn sliver_reorderable_list_properly_disposes_items() {
4173        test_widgets(|tester| {
4174            // Regression test for https://github.com/flutter/flutter/issues/105010
4175            let item_count = 5;
4176            let items = items(item_count);
4177            let show_list = Rc::new(Cell::new(false));
4178
4179            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
4180                move |_app, _context, set_state| {
4181                    if !show_list.get() {
4182                        let show_list = Rc::clone(&show_list);
4183                        return GestureDetector::new()
4184                            .on_tap(Listener::new(move |app| {
4185                                set_state(app, &mut |_app| show_list.set(true));
4186                            }))
4187                            .child(Text::new("Show list"))
4188                            .into_widget();
4189                    }
4190                    let builder_items = Rc::clone(&items);
4191                    let show_list = Rc::clone(&show_list);
4192                    Column::new()
4193                        .children([
4194                            Expanded::new(
4195                                CustomScrollView::new().slivers([SliverReorderableList::new(
4196                                    move |_app, _context, index| {
4197                                        ReorderableDragStartListener::new(
4198                                            test_list_tile(Text::new(format!(
4199                                                "item {}",
4200                                                builder_items.borrow()[index as usize]
4201                                            ))),
4202                                            index,
4203                                        )
4204                                        .key(ValueKey::new(format!("item-{index}")).into())
4205                                        .into_widget()
4206                                    },
4207                                    item_count,
4208                                )
4209                                .on_reorder_item(|_app, _from, _to| {})
4210                                .into_widget()]),
4211                            )
4212                            .into_widget(),
4213                            GestureDetector::new()
4214                                .on_tap(Listener::new(move |app| {
4215                                    set_state(app, &mut |_app| show_list.set(false));
4216                                }))
4217                                .child(Text::new("Close list"))
4218                                .into_widget(),
4219                        ])
4220                        .into_widget()
4221                },
4222            )));
4223
4224            tester.tap(find::text("Show list"));
4225            tester.pump_and_settle();
4226
4227            let item_0 = || find::text("item 0");
4228            expect(tester, &item_0(), finds_one_widget());
4229
4230            // Start gesture on first item without drag up event.
4231            let at = tester.get_center(item_0());
4232            let mut drag = start_gesture(tester, at);
4233            tester.move_by(&mut drag, Offset::new(0.0, 200.0), true);
4234            tester.pump();
4235
4236            tester.tap(find::text("Close list"));
4237            tester.pump_and_settle();
4238
4239            expect(tester, &item_0(), finds_nothing());
4240        });
4241    }
4242
4243    #[test]
4244    fn null_check_error_when_dragging_and_dropping_last_element_into_last_index_with_reverse_true()
4245    {
4246        test_widgets(|tester| {
4247            // Regression test for https://github.com/flutter/flutter/issues/132077
4248            let item_count = 5;
4249            let items: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(
4250                (0..item_count)
4251                    .map(|index| format!("Item {}", index + 1))
4252                    .collect(),
4253            ));
4254
4255            let reorder_items = Rc::clone(&items);
4256            let builder_items = Rc::clone(&items);
4257            tester.pump_widget(
4258                TestWidgetsApp::new().home(
4259                    ReorderableList::new(
4260                        move |_app, _context, index| {
4261                            ReorderableDragStartListener::new(
4262                                test_list_tile(Text::new(
4263                                    builder_items.borrow()[index as usize].clone(),
4264                                )),
4265                                index,
4266                            )
4267                            .key(ValueKey::new(format!("{index}")).into())
4268                            .into_widget()
4269                        },
4270                        item_count,
4271                    )
4272                    .on_reorder_item(move |_app, old_index, new_index| {
4273                        let mut items = reorder_items.borrow_mut();
4274                        let item = items.remove(old_index as usize);
4275                        items.insert(new_index as usize, item);
4276                    })
4277                    .reverse(true),
4278                ),
4279            );
4280
4281            // Start gesture on last item
4282            let at = tester.get_center(find::text("Item 5"));
4283            let mut drag = start_gesture(tester, at);
4284            tester.pump_by(K_LONG_PRESS_TIMEOUT);
4285
4286            // Drag to move up the last item, and drop at the last index
4287            tester.move_by(&mut drag, Offset::new(0.0, -50.0), true);
4288            tester.pump();
4289            tester.up(&drag);
4290            tester.pump_and_settle();
4291        });
4292    }
4293
4294    #[test]
4295    fn tests_that_the_item_position_is_correct_when_prototype_item_or_item_extent_are_set() {
4296        test_widgets(|tester| {
4297            fn test_for(
4298                tester: &mut WidgetTester,
4299                prototype_item: Option<WidgetRef>,
4300                item_extent: Option<f64>,
4301            ) {
4302                let mut list = SliverReorderableList::new(
4303                    |_app, _context, index| {
4304                        ReorderableDragStartListener::new(
4305                            SizedBox::new()
4306                                .height(100.0)
4307                                .child(Text::new(index.to_string())),
4308                            index,
4309                        )
4310                        .key(ValueKey::new(index).into())
4311                        .into_widget()
4312                    },
4313                    5,
4314                )
4315                .on_reorder_item(|_app, _from, _to| {});
4316                list.item_extent = item_extent;
4317                list.prototype_item = prototype_item;
4318                tester.pump_widget(
4319                    TestWidgetsApp::new()
4320                        .home(CustomScrollView::new().slivers([list.into_widget()])),
4321                );
4322
4323                let at = tester.get_center(find::text("0"));
4324                let mut drag = start_gesture(tester, at);
4325                tester.pump_by(K_LONG_PRESS_TIMEOUT);
4326                tester.move_by(&mut drag, Offset::new(0.0, 20.0), true);
4327                tester.pump();
4328                assert_eq!(
4329                    tester.get_top_left(find::text("1")),
4330                    Offset::new(0.0, 100.0)
4331                );
4332                tester.up(&drag);
4333                tester.pump_and_settle();
4334            }
4335
4336            test_for(tester, None, None);
4337            test_for(
4338                tester,
4339                Some(
4340                    SizedBox::new()
4341                        .height(100.0)
4342                        .width(100.0)
4343                        .child(Text::new("prototype"))
4344                        .into_widget(),
4345                ),
4346                None,
4347            );
4348            test_for(tester, None, Some(100.0));
4349        });
4350    }
4351
4352    #[test]
4353    fn the_item_being_dragged_will_not_be_affected_by_layout_constraints() {
4354        test_widgets(|tester| {
4355            let item_layout_constraints: Rc<RefCell<HashMap<i32, BoxConstraints>>> = Rc::default();
4356            let recorded = Rc::clone(&item_layout_constraints);
4357            tester.pump_widget(
4358                TestWidgetsApp::new().home(
4359                    CustomScrollView::new().slivers([SliverReorderableList::new(
4360                        move |_app, _context, index| {
4361                            let recorded = Rc::clone(&recorded);
4362                            LayoutBuilder::new(move |_app, _context, constraints| {
4363                                recorded
4364                                    .borrow_mut()
4365                                    .insert(index, constraints.constraints());
4366                                SizedBox::new()
4367                                    .height(100.0)
4368                                    .child(ReorderableDragStartListener::new(
4369                                        Text::new(index.to_string()),
4370                                        index,
4371                                    ))
4372                                    .into_widget()
4373                            })
4374                            .key(ValueKey::new(index).into())
4375                            .into_widget()
4376                        },
4377                        5,
4378                    )
4379                    .on_reorder_item(|_app, _from, _to| {})
4380                    .into_widget()]),
4381                ),
4382            );
4383            let pre_drag_layout_constraints = item_layout_constraints.borrow().clone();
4384            item_layout_constraints.borrow_mut().clear();
4385            let at = tester.get_center(find::text("0"));
4386            let mut drag = start_gesture(tester, at);
4387            tester.pump_by(K_LONG_PRESS_TIMEOUT);
4388            tester.move_by(&mut drag, Offset::new(0.0, 20.0), true);
4389            tester.pump();
4390            assert_eq!(
4391                *item_layout_constraints.borrow(),
4392                pre_drag_layout_constraints
4393            );
4394            tester.up(&drag);
4395            tester.pump_and_settle();
4396        });
4397    }
4398
4399    #[test]
4400    fn drag_boundary_defines_the_boundary_for_reorderable_list() {
4401        test_widgets(|tester| {
4402            tester.pump_widget(
4403                TestWidgetsApp::new().home(
4404                    Align::new().alignment(AlignmentGeometry::TOP_LEFT).child(
4405                        Container::new()
4406                            .margin(EdgeInsetsGeometry::only(0.0, 100.0, 0.0, 0.0))
4407                            .height(300.0)
4408                            .child(DragBoundary::new(
4409                                CustomScrollView::new().slivers([SliverReorderableList::new(
4410                                    |_app, _context, index| {
4411                                        ReorderableDragStartListener::new(
4412                                            Text::new(index.to_string()),
4413                                            index,
4414                                        )
4415                                        .key(ValueKey::new(index).into())
4416                                        .into_widget()
4417                                    },
4418                                    5,
4419                                )
4420                                .on_reorder_item(|_app, _from, _to| {})
4421                                .into_widget()]),
4422                            )),
4423                    ),
4424                ),
4425            );
4426            let at = tester.get_center(find::text("0"));
4427            let mut drag = start_gesture(tester, at);
4428            tester.pump_by(K_LONG_PRESS_TIMEOUT);
4429            tester.move_by(&mut drag, Offset::new(0.0, -400.0), true);
4430            tester.pump_and_settle();
4431            assert_eq!(
4432                tester.get_top_left(find::text("0")),
4433                Offset::new(0.0, 100.0)
4434            );
4435            tester.up(&drag);
4436            tester.pump_and_settle();
4437
4438            let at = tester.get_center(find::text("0"));
4439            let mut drag = start_gesture(tester, at);
4440            tester.pump_by(K_LONG_PRESS_TIMEOUT);
4441            tester.move_by(&mut drag, Offset::new(0.0, 800.0), true);
4442            tester.pump_and_settle();
4443            assert_eq!(
4444                tester.get_bottom_left(find::text("0")),
4445                Offset::new(0.0, 400.0)
4446            );
4447            tester.up(&drag);
4448            tester.pump_and_settle();
4449        });
4450    }
4451
4452    #[test]
4453    fn reorderable_list_does_not_crash_at_zero_area() {
4454        test_widgets(|tester| {
4455            tester.pump_widget(
4456                TestWidgetsApp::new().home(
4457                    Center::new().child(
4458                        SizedBox::shrink().child(
4459                            ReorderableList::new(
4460                                |_app, _context, _index| {
4461                                    Text::new("X")
4462                                        .key(ValueKey::new("x".to_string()).into())
4463                                        .into_widget()
4464                                },
4465                                3,
4466                            )
4467                            .on_reorder_item(|_app, _from, _to| {}),
4468                        ),
4469                    ),
4470                ),
4471            );
4472            assert_eq!(
4473                tester.get_size(find::by_type::<ReorderableList>()),
4474                Size::ZERO
4475            );
4476        });
4477    }
4478
4479    #[test]
4480    fn reorderable_drag_start_listener_does_not_crash_at_zero_area() {
4481        test_widgets(|tester| {
4482            tester.pump_widget(TestWidgetsApp::new().home(Center::new().child(
4483                SizedBox::shrink().child(ReorderableDragStartListener::new(Text::new("X"), 1)),
4484            )));
4485            assert_eq!(
4486                tester.get_size(find::by_type::<ReorderableDragStartListener>()),
4487                Size::ZERO
4488            );
4489        });
4490    }
4491
4492    #[test]
4493    fn reorderable_delayed_drag_start_listener_does_not_crash_at_zero_area() {
4494        test_widgets(|tester| {
4495            tester.pump_widget(
4496                TestWidgetsApp::new().home(
4497                    Center::new().child(
4498                        SizedBox::shrink()
4499                            .child(ReorderableDelayedDragStartListener::new(Text::new("X"), 1)),
4500                    ),
4501                ),
4502            );
4503            assert_eq!(
4504                tester.get_size(find::by_type::<ReorderableDelayedDragStartListener>()),
4505                Size::ZERO
4506            );
4507        });
4508    }
4509
4510    /// Upstream regression: a taller item dragged over a shorter one keeps the gap in place
4511    /// while the pointer creeps upward, instead of flipping it back on small movements.
4512    #[test]
4513    fn sliver_reorderable_list_gap_does_not_flip_when_dragging_a_taller_item_over_a_shorter_one() {
4514        const ITEM_HEIGHTS: [f64; 8] = [68.0, 85.0, 126.0, 97.0, 54.0, 106.0, 110.0, 119.0];
4515        test_widgets(|tester| {
4516            let items: Rc<RefCell<Vec<i32>>> = Rc::new(RefCell::new((0..8).collect()));
4517            let builder_items = Rc::clone(&items);
4518            let reorder_items = Rc::clone(&items);
4519            tester.pump_widget(TestWidgetsApp::new().home(StatefulBuilder::new(
4520                move |_app, _context, set_state: StateSetter| {
4521                    let builder_items = Rc::clone(&builder_items);
4522                    let reorder_items = Rc::clone(&reorder_items);
4523                    let item_count = builder_items.borrow().len() as i32;
4524                    CustomScrollView::new()
4525                        .slivers([SliverReorderableList::new(
4526                            move |_app, _context, index| {
4527                                let item = builder_items.borrow()[index as usize];
4528                                SizedBox::new()
4529                                    .key(ValueKey::new(item).into())
4530                                    .height(ITEM_HEIGHTS[item as usize])
4531                                    .child(ReorderableDragStartListener::new(
4532                                        Text::new(format!("item {item}")),
4533                                        index,
4534                                    ))
4535                                    .into_widget()
4536                            },
4537                            item_count,
4538                        )
4539                        .on_reorder_item(move |app, from_index, to_index| {
4540                            let reorder_items = Rc::clone(&reorder_items);
4541                            set_state(app, &mut |_app| {
4542                                let mut items = reorder_items.borrow_mut();
4543                                let item = items.remove(from_index as usize);
4544                                items.insert(to_index as usize, item);
4545                            });
4546                        })
4547                        .into_widget()])
4548                        .into_widget()
4549                },
4550            )));
4551
4552            let item4 = find::text("item 4");
4553            let item5 = find::text("item 5");
4554            assert_eq!(tester.get_top_left(&item4).dy(), 376.0);
4555            assert_eq!(tester.get_top_left(&item5).dy(), 430.0);
4556
4557            // Pick up item 5 (106 tall) and move it up into the top half of item 4 (54 tall).
4558            let mut pointer = TestPointer::touch(tester.next_pointer());
4559            tester.down(&mut pointer, tester.get_center(&item5));
4560            tester.pump_by(K_PRESS_TIMEOUT);
4561            tester.move_by(&mut pointer, Offset::new(0.0, -48.5), true);
4562            tester.pump_and_settle();
4563
4564            // Item 4 is pushed down by item 5's extent: 376 + 106.
4565            let pushed_down = tester.get_top_left(&item4).dy();
4566            assert_eq!(pushed_down, 482.0);
4567
4568            // Creep upward half a pixel at a time; item 4 must not flip back to 376.
4569            for _ in 0..8 {
4570                tester.move_by(&mut pointer, Offset::new(0.0, -0.5), true);
4571                tester.pump_and_settle();
4572                assert_eq!(tester.get_top_left(&item4).dy(), pushed_down);
4573            }
4574
4575            tester.up(&pointer);
4576            tester.pump_and_settle();
4577        });
4578    }
4579}