Skip to main content

waft_widgets/widgets/
drag_target.rs

1//! Flutter counterpart: `widgets/drag_target.dart`.
2
3use std::any::Any;
4use std::fmt;
5use std::rc::Rc;
6use std::time::Duration;
7
8use waft_embedder::{Offset, ViewId};
9use waft_foundation::{App, Handle, HandleId, Listener, OptionRetained};
10use waft_gestures::*;
11use waft_painting::Axis;
12use waft_rendering::{BoxHitTestEntry, HitTestBehavior, RenderMetaData};
13use waft_services::HapticFeedback;
14
15use crate::*;
16use waft_foundation::Ref;
17
18/// Signature for determining whether a drag target will accept the given data.
19pub type DragTargetWillAccept<T> = Rc<dyn Fn(&mut App, Option<Rc<T>>) -> bool>;
20
21/// Signature for determining whether a drag target will accept the given drag details.
22pub type DragTargetWillAcceptWithDetails<T> = Rc<dyn Fn(&mut App, DragTargetDetails<T>) -> bool>;
23
24/// Signature for causing a drag target to accept the given data.
25pub type DragTargetAccept<T> = Rc<dyn Fn(&mut App, Rc<T>)>;
26
27/// Signature for causing a drag target to accept the given drag details.
28pub type DragTargetAcceptWithDetails<T> = Rc<dyn Fn(&mut App, DragTargetDetails<T>)>;
29
30/// Signature for building a drag target from its candidate and rejected data.
31pub type DragTargetBuilder<T> =
32    Rc<dyn Fn(&mut App, BuildContext, Vec<Option<Rc<T>>>, Vec<Option<Rc<dyn Any>>>) -> WidgetRef>;
33
34/// Signature for when a Draggable is dragged across the screen.
35pub type DragUpdateCallback = Rc<dyn Fn(&mut App, DragUpdateDetails)>;
36
37/// Signature for a draggable dropped without being accepted by a target.
38pub type DraggableCanceledCallback = Rc<dyn Fn(&mut App, Velocity, Offset)>;
39
40/// Signature for when the draggable is dropped.
41pub type DragEndCallback = Rc<dyn Fn(&mut App, DraggableDetails)>;
42
43/// Signature for when a Draggable leaves a DragTarget.
44pub type DragTargetLeave<T> = Rc<dyn Fn(&mut App, Option<Rc<T>>)>;
45
46/// Signature for when a Draggable moves within a DragTarget.
47pub type DragTargetMove<T> = Rc<dyn Fn(&mut App, DragTargetDetails<T>)>;
48
49/// Signature for the strategy that determines the drag start point.
50pub type DragAnchorStrategy<T> =
51    Rc<dyn Fn(&mut App, &Draggable<T>, BuildContext, Offset) -> Offset>;
52
53/// Display the feedback anchored at the position of the original child.
54pub fn child_drag_anchor_strategy<T: 'static>(
55    app: &mut App,
56    _draggable: &Draggable<T>,
57    context: BuildContext,
58    position: Offset,
59) -> Offset {
60    context
61        .find_render_object(app)
62        .unwrap()
63        .as_box()
64        .unwrap()
65        .global_to_local(app, position, None)
66}
67
68/// Display the feedback anchored at the position of the touch that started the drag.
69pub fn pointer_drag_anchor_strategy<T: 'static>(
70    _app: &mut App,
71    _draggable: &Draggable<T>,
72    _context: BuildContext,
73    _position: Offset,
74) -> Offset {
75    Offset::ZERO
76}
77
78/// A widget that can be dragged from to a DragTarget.
79///
80/// Active drags and their feedback survive removal of the source widget.
81pub struct Draggable<T: 'static> {
82    /// Controls how one widget replaces another widget in the tree.
83    pub key: Option<KeyRef>,
84
85    /// The data that was dropped onto this `DragTarget`.
86    pub data: Option<Rc<T>>,
87
88    /// The `Axis` to restrict this draggable's movement, if specified.
89    ///
90    /// When axis is set to `Axis.horizontal`, this widget can only be dragged
91    /// horizontally. Behavior is similar for `Axis.vertical`.
92    ///
93    /// Defaults to allowing drag on both `Axis.horizontal` and `Axis.vertical`.
94    ///
95    /// When null, allows drag on both `Axis.horizontal` and `Axis.vertical`.
96    ///
97    /// For the direction of gestures this widget competes with to start a drag
98    /// event, see `Draggable.affinity`.
99    pub axis: Option<Axis>,
100
101    /// The widget below this widget in the tree.
102    ///
103    /// This widget displays `child` when zero drags are under way. If
104    /// `childWhenDragging` is non-null, this widget instead displays
105    /// `childWhenDragging` when one or more drags are underway. Otherwise, this
106    /// widget always displays `child`.
107    ///
108    /// The `feedback` widget is shown under the pointer when a drag is under way.
109    ///
110    /// To limit the number of simultaneous drags on multitouch devices, see
111    /// `maxSimultaneousDrags`.
112    ///
113    /// {@macro flutter.widgets.ProxyWidget.child}
114    pub child: WidgetRef,
115
116    /// The widget to display instead of `child` when one or more drags are under way.
117    ///
118    /// If this is null, then this widget will always display `child` (and so the
119    /// drag source representation will not change while a drag is under
120    /// way).
121    ///
122    /// The `feedback` widget is shown under the pointer when a drag is under way.
123    ///
124    /// To limit the number of simultaneous drags on multitouch devices, see
125    /// `maxSimultaneousDrags`.
126    pub child_when_dragging: Option<WidgetRef>,
127
128    /// The widget to show under the pointer when a drag is under way.
129    ///
130    /// See `child` and `childWhenDragging` for information about what is shown
131    /// at the location of the `Draggable` itself when a drag is under way.
132    pub feedback: WidgetRef,
133
134    /// The feedbackOffset can be used to set the hit test target point for the
135    /// purposes of finding a drag target. It is especially useful if the feedback
136    /// is transformed compared to the child.
137    pub feedback_offset: Offset,
138
139    /// A strategy that is used by this draggable to get the anchor offset when it
140    /// is dragged.
141    ///
142    /// The anchor offset refers to the distance between the users' fingers and
143    /// the `feedback` widget when this draggable is dragged.
144    ///
145    /// This property's value is a function that implements `DragAnchorStrategy`.
146    /// There are two built-in functions that can be used:
147    ///
148    ///  * `childDragAnchorStrategy`, which displays the feedback anchored at the
149    ///    position of the original child.
150    ///
151    ///  * `pointerDragAnchorStrategy`, which displays the feedback anchored at the
152    ///    position of the touch that started the drag.
153    ///
154    /// Defaults to `childDragAnchorStrategy`.
155    pub drag_anchor_strategy: DragAnchorStrategy<T>,
156
157    /// Whether the semantics of the `feedback` widget is ignored when building
158    /// the semantics tree.
159    ///
160    /// This value should be set to false when the `feedback` widget is intended
161    /// to be the same object as the `child`. Placing a `GlobalKey` on this
162    /// widget will ensure semantic focus is kept on the element as it moves in
163    /// and out of the feedback position.
164    ///
165    /// Defaults to true.
166    pub ignoring_feedback_semantics: bool,
167
168    /// Whether the `feedback` widget is ignored during hit testing.
169    ///
170    /// Regardless of whether this widget is ignored during hit testing, it will
171    /// still consume space during layout and be visible during painting.
172    ///
173    /// Defaults to true.
174    pub ignoring_feedback_pointer: bool,
175
176    /// Controls how this widget competes with other gestures to initiate a drag.
177    ///
178    /// If affinity is null, this widget initiates a drag as soon as it recognizes
179    /// a tap down gesture, regardless of any directionality. If affinity is
180    /// horizontal (or vertical), then this widget will compete with other
181    /// horizontal (or vertical, respectively) gestures.
182    ///
183    /// For example, if this widget is placed in a vertically scrolling region and
184    /// has horizontal affinity, pointer motion in the vertical direction will
185    /// result in a scroll and pointer motion in the horizontal direction will
186    /// result in a drag. Conversely, if the widget has a null or vertical
187    /// affinity, pointer motion in any direction will result in a drag rather
188    /// than in a scroll because the draggable widget, being the more specific
189    /// widget, will out-compete the `Scrollable` for vertical gestures.
190    ///
191    /// For the directions this widget can be dragged in after the drag event
192    /// starts, see `Draggable.axis`.
193    pub affinity: Option<Axis>,
194
195    /// How many simultaneous drags to support.
196    ///
197    /// When null, no limit is applied. Set this to 1 if you want to only allow
198    /// the drag source to have one item dragged at a time. Set this to 0 if you
199    /// want to prevent the draggable from actually being dragged.
200    ///
201    /// If you set this property to 1, consider supplying an "empty" widget for
202    /// `childWhenDragging` to create the illusion of actually moving `child`.
203    pub max_simultaneous_drags: Option<usize>,
204
205    /// Called when the draggable starts being dragged.
206    pub on_drag_started: Option<Listener>,
207
208    /// Called when the draggable is dragged.
209    ///
210    /// This function will only be called while this widget is still mounted to
211    /// the tree (i.e. `State.mounted` is true), and if this widget has actually moved.
212    pub on_drag_update: Option<DragUpdateCallback>,
213
214    /// Called when the draggable is dropped without being accepted by a `DragTarget`.
215    ///
216    /// This function might be called after this widget has been removed from the
217    /// tree. For example, if a drag was in progress when this widget was removed
218    /// from the tree and the drag ended up being canceled, this callback will
219    /// still be called. For this reason, implementations of this callback might
220    /// need to check `State.mounted` to check whether the state receiving the
221    /// callback is still in the tree.
222    pub on_draggable_canceled: Option<DraggableCanceledCallback>,
223
224    /// Called when the draggable is dropped and accepted by a `DragTarget`.
225    ///
226    /// This function might be called after this widget has been removed from the
227    /// tree. For example, if a drag was in progress when this widget was removed
228    /// from the tree and the drag ended up completing, this callback will
229    /// still be called. For this reason, implementations of this callback might
230    /// need to check `State.mounted` to check whether the state receiving the
231    /// callback is still in the tree.
232    pub on_drag_completed: Option<Listener>,
233
234    /// Called when the draggable is dropped.
235    ///
236    /// The velocity and offset at which the pointer was moving when it was
237    /// dropped is available in the `DraggableDetails`. Also included in the
238    /// `details` is whether the draggable's `DragTarget` accepted it.
239    ///
240    /// This function will only be called while this widget is still mounted to
241    /// the tree (i.e. `State.mounted` is true).
242    pub on_drag_end: Option<DragEndCallback>,
243
244    /// Whether the feedback widget will be put on the root `Overlay`.
245    ///
246    /// When false, the feedback widget will be put on the closest `Overlay`. When
247    /// true, the `feedback` widget will be put on the farthest (aka root)
248    /// `Overlay`.
249    ///
250    /// Defaults to false.
251    pub root_overlay: bool,
252
253    /// How to behave during hit testing.
254    ///
255    /// Defaults to `HitTestBehavior.translucent`.
256    pub hit_test_behavior: HitTestBehavior,
257
258    /// {@macro flutter.gestures.multidrag._allowedButtonsFilter}
259    pub allowed_buttons_filter: Option<AllowedButtonsFilter>,
260}
261
262impl<T: 'static> Clone for Draggable<T> {
263    fn clone(&self) -> Self {
264        Self {
265            key: self.key.clone(),
266            data: self.data.clone(),
267            axis: self.axis,
268            child: self.child.clone(),
269            child_when_dragging: self.child_when_dragging.clone(),
270            feedback: self.feedback.clone(),
271            feedback_offset: self.feedback_offset,
272            drag_anchor_strategy: self.drag_anchor_strategy.clone(),
273            ignoring_feedback_semantics: self.ignoring_feedback_semantics,
274            ignoring_feedback_pointer: self.ignoring_feedback_pointer,
275            affinity: self.affinity,
276            max_simultaneous_drags: self.max_simultaneous_drags,
277            on_drag_started: self.on_drag_started.clone(),
278            on_drag_update: self.on_drag_update.clone(),
279            on_draggable_canceled: self.on_draggable_canceled.clone(),
280            on_drag_completed: self.on_drag_completed.clone(),
281            on_drag_end: self.on_drag_end.clone(),
282            root_overlay: self.root_overlay,
283            hit_test_behavior: self.hit_test_behavior,
284            allowed_buttons_filter: self.allowed_buttons_filter.clone(),
285        }
286    }
287}
288
289impl<T: 'static> fmt::Debug for Draggable<T> {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        f.debug_struct("Draggable").finish_non_exhaustive()
292    }
293}
294
295impl<T: 'static> Draggable<T> {
296    /// Creates a draggable with its normal child and drag feedback.
297    #[cfg_attr(debug_assertions, track_caller)]
298    pub fn new<C, F>(child: impl IntoWidget<C>, feedback: impl IntoWidget<F>) -> Self {
299        Self {
300            key: None,
301            data: None,
302            axis: None,
303            child: child.into_widget(),
304            child_when_dragging: None,
305            feedback: feedback.into_widget(),
306            feedback_offset: Offset::ZERO,
307            drag_anchor_strategy: Rc::new(child_drag_anchor_strategy::<T>),
308            ignoring_feedback_semantics: true,
309            ignoring_feedback_pointer: true,
310            affinity: None,
311            max_simultaneous_drags: None,
312            on_drag_started: None,
313            on_drag_update: None,
314            on_draggable_canceled: None,
315            on_drag_completed: None,
316            on_drag_end: None,
317            root_overlay: false,
318            hit_test_behavior: HitTestBehavior::DeferToChild,
319            allowed_buttons_filter: None,
320        }
321    }
322
323    /// Sets `key` for this draggable.
324    pub fn key(mut self, value: KeyRef) -> Self {
325        self.key = Some(value);
326        self
327    }
328
329    /// Sets `data` for this draggable.
330    pub fn data(mut self, value: T) -> Self {
331        self.data = Some(Rc::new(value));
332        self
333    }
334
335    /// Sets `axis` for this draggable.
336    pub fn axis(mut self, value: Axis) -> Self {
337        self.axis = Some(value);
338        self
339    }
340
341    /// Sets `child_when_dragging` for this draggable.
342    #[cfg_attr(debug_assertions, track_caller)]
343    pub fn child_when_dragging<K>(mut self, value: impl IntoWidget<K>) -> Self {
344        self.child_when_dragging = Some(value.into_widget());
345        self
346    }
347
348    /// Sets `feedback_offset` for this draggable.
349    pub fn feedback_offset(mut self, value: Offset) -> Self {
350        self.feedback_offset = value;
351        self
352    }
353
354    /// Sets `drag_anchor_strategy` for this draggable.
355    pub fn drag_anchor_strategy(mut self, value: DragAnchorStrategy<T>) -> Self {
356        self.drag_anchor_strategy = value;
357        self
358    }
359
360    /// Sets `ignoring_feedback_semantics` for this draggable.
361    pub fn ignoring_feedback_semantics(mut self, value: bool) -> Self {
362        self.ignoring_feedback_semantics = value;
363        self
364    }
365
366    /// Sets `ignoring_feedback_pointer` for this draggable.
367    pub fn ignoring_feedback_pointer(mut self, value: bool) -> Self {
368        self.ignoring_feedback_pointer = value;
369        self
370    }
371
372    /// Sets `affinity` for this draggable.
373    pub fn affinity(mut self, value: Axis) -> Self {
374        self.affinity = Some(value);
375        self
376    }
377
378    /// Sets `max_simultaneous_drags` for this draggable.
379    pub fn max_simultaneous_drags(mut self, value: usize) -> Self {
380        self.max_simultaneous_drags = Some(value);
381        self
382    }
383
384    /// Sets `on_drag_started` for this draggable.
385    pub fn on_drag_started(mut self, value: Listener) -> Self {
386        self.on_drag_started = Some(value);
387        self
388    }
389
390    /// Sets `on_drag_update` for this draggable.
391    pub fn on_drag_update(mut self, value: DragUpdateCallback) -> Self {
392        self.on_drag_update = Some(value);
393        self
394    }
395
396    /// Sets `on_draggable_canceled` for this draggable.
397    pub fn on_draggable_canceled(mut self, value: DraggableCanceledCallback) -> Self {
398        self.on_draggable_canceled = Some(value);
399        self
400    }
401
402    /// Sets `on_drag_completed` for this draggable.
403    pub fn on_drag_completed(mut self, value: Listener) -> Self {
404        self.on_drag_completed = Some(value);
405        self
406    }
407
408    /// Sets `on_drag_end` for this draggable.
409    pub fn on_drag_end(mut self, value: DragEndCallback) -> Self {
410        self.on_drag_end = Some(value);
411        self
412    }
413
414    /// Sets `root_overlay` for this draggable.
415    pub fn root_overlay(mut self, value: bool) -> Self {
416        self.root_overlay = value;
417        self
418    }
419
420    /// Sets `hit_test_behavior` for this draggable.
421    pub fn hit_test_behavior(mut self, value: HitTestBehavior) -> Self {
422        self.hit_test_behavior = value;
423        self
424    }
425
426    /// Sets `allowed_buttons_filter` for this draggable.
427    pub fn allowed_buttons_filter(mut self, value: AllowedButtonsFilter) -> Self {
428        self.allowed_buttons_filter = Some(value);
429        self
430    }
431}
432
433/// The Draggable superclass interface; a subclass overrides `create_recognizer`.
434pub trait DraggableWidget: StatefulWidget<State = DraggableState<Self>> + Clone {
435    type Data: 'static;
436
437    fn draggable(&self) -> &Draggable<Self::Data>;
438
439    fn create_recognizer(
440        &self,
441        app: &mut App,
442        on_start: GestureMultiDragStartCallback,
443    ) -> MultiDragRecognizerRef {
444        let draggable = self.draggable();
445        let recognizer: MultiDragRecognizerRef = match draggable.affinity {
446            Some(Axis::Horizontal) => HorizontalMultiDragGestureRecognizer::new(app).into_erased(),
447            Some(Axis::Vertical) => VerticalMultiDragGestureRecognizer::new(app).into_erased(),
448            None => ImmediateMultiDragGestureRecognizer::new(app).into_erased(),
449        };
450        if let Some(filter) = draggable.allowed_buttons_filter.clone() {
451            recognizer.set_allowed_buttons_filter(app, filter);
452        }
453        recognizer.set_on_start(app, Some(on_start));
454        recognizer
455    }
456}
457
458impl<T: 'static> DraggableWidget for Draggable<T> {
459    type Data = T;
460
461    fn draggable(&self) -> &Self {
462        self
463    }
464}
465
466impl<T: 'static> StatefulWidget for Draggable<T> {
467    type State = DraggableState<Self>;
468
469    fn key(&self) -> Option<&KeyRef> {
470        self.key.as_ref()
471    }
472
473    fn create_state(&self) -> Self::State {
474        DraggableState::new()
475    }
476}
477
478/// Makes its child draggable starting from long press.
479pub struct LongPressDraggable<T: 'static> {
480    /// The Draggable superclass configuration.
481    pub draggable: Draggable<T>,
482
483    /// Whether haptic feedback should be triggered on drag start.
484    pub haptic_feedback_on_start: bool,
485
486    /// The duration that a user has to press down before a long press is registered.
487    ///
488    /// Defaults to `kLongPressTimeout`.
489    pub delay: Duration,
490}
491
492impl<T: 'static> Clone for LongPressDraggable<T> {
493    fn clone(&self) -> Self {
494        Self {
495            draggable: self.draggable.clone(),
496            haptic_feedback_on_start: self.haptic_feedback_on_start,
497            delay: self.delay,
498        }
499    }
500}
501
502impl<T: 'static> fmt::Debug for LongPressDraggable<T> {
503    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504        f.debug_struct("LongPressDraggable").finish_non_exhaustive()
505    }
506}
507
508impl<T: 'static> LongPressDraggable<T> {
509    /// Creates a draggable with its normal child and drag feedback.
510    #[cfg_attr(debug_assertions, track_caller)]
511    pub fn new<C, F>(child: impl IntoWidget<C>, feedback: impl IntoWidget<F>) -> Self {
512        Self {
513            draggable: Draggable::new(child, feedback),
514            haptic_feedback_on_start: true,
515            delay: K_LONG_PRESS_TIMEOUT,
516        }
517    }
518
519    /// Sets `delay` for this draggable.
520    pub fn delay(mut self, value: Duration) -> Self {
521        self.delay = value;
522        self
523    }
524
525    /// Sets `haptic_feedback_on_start` for this draggable.
526    pub fn haptic_feedback_on_start(mut self, value: bool) -> Self {
527        self.haptic_feedback_on_start = value;
528        self
529    }
530
531    /// Sets `key` for this draggable.
532    pub fn key(mut self, value: KeyRef) -> Self {
533        self.draggable.key = Some(value);
534        self
535    }
536
537    /// Sets `data` for this draggable.
538    pub fn data(mut self, value: T) -> Self {
539        self.draggable.data = Some(Rc::new(value));
540        self
541    }
542
543    /// Sets `axis` for this draggable.
544    pub fn axis(mut self, value: Axis) -> Self {
545        self.draggable.axis = Some(value);
546        self
547    }
548
549    /// Sets `child_when_dragging` for this draggable.
550    #[cfg_attr(debug_assertions, track_caller)]
551    pub fn child_when_dragging<K>(mut self, value: impl IntoWidget<K>) -> Self {
552        self.draggable.child_when_dragging = Some(value.into_widget());
553        self
554    }
555
556    /// Sets `feedback_offset` for this draggable.
557    pub fn feedback_offset(mut self, value: Offset) -> Self {
558        self.draggable.feedback_offset = value;
559        self
560    }
561
562    /// Sets `drag_anchor_strategy` for this draggable.
563    pub fn drag_anchor_strategy(mut self, value: DragAnchorStrategy<T>) -> Self {
564        self.draggable.drag_anchor_strategy = value;
565        self
566    }
567
568    /// Sets `ignoring_feedback_semantics` for this draggable.
569    pub fn ignoring_feedback_semantics(mut self, value: bool) -> Self {
570        self.draggable.ignoring_feedback_semantics = value;
571        self
572    }
573
574    /// Sets `ignoring_feedback_pointer` for this draggable.
575    pub fn ignoring_feedback_pointer(mut self, value: bool) -> Self {
576        self.draggable.ignoring_feedback_pointer = value;
577        self
578    }
579
580    /// Sets `max_simultaneous_drags` for this draggable.
581    pub fn max_simultaneous_drags(mut self, value: usize) -> Self {
582        self.draggable.max_simultaneous_drags = Some(value);
583        self
584    }
585
586    /// Sets `on_drag_started` for this draggable.
587    pub fn on_drag_started(mut self, value: Listener) -> Self {
588        self.draggable.on_drag_started = Some(value);
589        self
590    }
591
592    /// Sets `on_drag_update` for this draggable.
593    pub fn on_drag_update(mut self, value: DragUpdateCallback) -> Self {
594        self.draggable.on_drag_update = Some(value);
595        self
596    }
597
598    /// Sets `on_draggable_canceled` for this draggable.
599    pub fn on_draggable_canceled(mut self, value: DraggableCanceledCallback) -> Self {
600        self.draggable.on_draggable_canceled = Some(value);
601        self
602    }
603
604    /// Sets `on_drag_completed` for this draggable.
605    pub fn on_drag_completed(mut self, value: Listener) -> Self {
606        self.draggable.on_drag_completed = Some(value);
607        self
608    }
609
610    /// Sets `on_drag_end` for this draggable.
611    pub fn on_drag_end(mut self, value: DragEndCallback) -> Self {
612        self.draggable.on_drag_end = Some(value);
613        self
614    }
615
616    /// Sets `root_overlay` for this draggable.
617    pub fn root_overlay(mut self, value: bool) -> Self {
618        self.draggable.root_overlay = value;
619        self
620    }
621
622    /// Sets `hit_test_behavior` for this draggable.
623    pub fn hit_test_behavior(mut self, value: HitTestBehavior) -> Self {
624        self.draggable.hit_test_behavior = value;
625        self
626    }
627
628    /// Sets `allowed_buttons_filter` for this draggable.
629    pub fn allowed_buttons_filter(mut self, value: AllowedButtonsFilter) -> Self {
630        self.draggable.allowed_buttons_filter = Some(value);
631        self
632    }
633}
634
635impl<T: 'static> DraggableWidget for LongPressDraggable<T> {
636    type Data = T;
637
638    fn draggable(&self) -> &Draggable<T> {
639        &self.draggable
640    }
641
642    fn create_recognizer(
643        &self,
644        app: &mut App,
645        on_start: GestureMultiDragStartCallback,
646    ) -> MultiDragRecognizerRef {
647        let recognizer = DelayedMultiDragGestureRecognizer::new(app);
648        recognizer.set_delay(app, self.delay);
649        let recognizer: MultiDragRecognizerRef = recognizer.into_erased();
650        if let Some(filter) = self.draggable.allowed_buttons_filter.clone() {
651            recognizer.set_allowed_buttons_filter(app, filter);
652        }
653        let haptic = self.haptic_feedback_on_start;
654        recognizer.set_on_start(
655            app,
656            Some(Rc::new(move |app, position| {
657                let result = on_start(app, position);
658                if result.is_some() && haptic {
659                    HapticFeedback::selection_click(app);
660                }
661                result
662            })),
663        );
664        recognizer
665    }
666}
667
668impl<T: 'static> StatefulWidget for LongPressDraggable<T> {
669    type State = DraggableState<Self>;
670
671    fn key(&self) -> Option<&KeyRef> {
672        self.draggable.key.as_ref()
673    }
674
675    fn create_state(&self) -> Self::State {
676        DraggableState::new()
677    }
678}
679
680/// Retains the recognizer until every active drag has ended, even after unmount.
681pub struct DraggableState<W: DraggableWidget> {
682    /// Native widget lifecycle and element association.
683    state: StateData<W>,
684
685    /// Stays alive after unmount until every drag listening to pointer events has ended.
686    recognizer: Option<MultiDragRecognizerRef>,
687
688    /// Number of active drag avatars retaining this state and recognizer.
689    active_count: usize,
690}
691
692impl<W: DraggableWidget> Default for DraggableState<W> {
693    /// Creates the same inactive state as `new`.
694    fn default() -> Self {
695        Self::new()
696    }
697}
698
699impl<W: DraggableWidget> DraggableState<W> {
700    /// Creates state for Draggable and widgets overriding its recognizer factory.
701    pub fn new() -> Self {
702        Self {
703            state: StateData::new(),
704            recognizer: None,
705            active_count: 0,
706        }
707    }
708
709    fn dispose_recognizer_if_inactive(self: Handle<Self>, app: &mut App) {
710        if app.get(self).active_count > 0 {
711            return;
712        }
713        if let Some(recognizer) = app.get_mut(self).recognizer.take() {
714            recognizer.dispose(app);
715        }
716    }
717
718    fn route_pointer(self: Handle<Self>, app: &mut App, event: PointerDownEvent) {
719        if self
720            .widget(app)
721            .draggable()
722            .max_simultaneous_drags
723            .is_some_and(|max| app.get(self).active_count >= max)
724        {
725            return;
726        }
727        app.get(self)
728            .recognizer
729            .handle()
730            .unwrap()
731            .add_pointer(app, &event);
732    }
733
734    fn start_drag(self: Handle<Self>, app: &mut App, position: Offset) -> Option<Rc<dyn Drag>> {
735        let widget = self.widget(app).draggable().clone();
736        if widget
737            .max_simultaneous_drags
738            .is_some_and(|max| app.get(self).active_count >= max)
739        {
740            return None;
741        }
742        let context = self.context(app);
743        let start = (widget.drag_anchor_strategy)(app, &widget, context, position);
744        self.set_state(app, |state| state.active_count += 1);
745        let retained = self.keep(app);
746        let overlay = Overlay::of(app, context, widget.root_overlay);
747        let view_id = View::of(app, context).id();
748        let avatar = DragAvatar::new(
749            app,
750            overlay,
751            widget.data.clone().map(|data| data as Rc<dyn Any>),
752            widget.axis,
753            position,
754            start,
755            widget.feedback.clone(),
756            widget.feedback_offset,
757            widget.ignoring_feedback_semantics,
758            widget.ignoring_feedback_pointer,
759            view_id,
760            Rc::new(move |app, details| {
761                if self.mounted(app)
762                    && let Some(callback) = self.widget(app).draggable().on_drag_update.clone()
763                {
764                    callback(app, details);
765                }
766            }),
767            Rc::new(move |app, velocity, offset, was_accepted| {
768                let _keep_alive = &retained;
769                if self.mounted(app) {
770                    self.set_state(app, |state| state.active_count -= 1);
771                } else {
772                    app.get_mut(self).active_count -= 1;
773                    self.dispose_recognizer_if_inactive(app);
774                }
775                let widget = self.widget(app).draggable().clone();
776                if self.mounted(app)
777                    && let Some(callback) = widget.on_drag_end
778                {
779                    callback(
780                        app,
781                        DraggableDetails {
782                            was_accepted,
783                            velocity,
784                            offset,
785                        },
786                    );
787                }
788                if was_accepted
789                    && let Some(callback) = self.widget(app).draggable().on_drag_completed.clone()
790                {
791                    callback.call(app);
792                }
793                if !was_accepted
794                    && let Some(callback) =
795                        self.widget(app).draggable().on_draggable_canceled.clone()
796                {
797                    callback(app, velocity, offset);
798                }
799            }),
800        );
801        if let Some(callback) = widget.on_drag_started {
802            callback.call(app);
803        }
804        Some(Rc::new(avatar))
805    }
806}
807
808impl<W: DraggableWidget> State for DraggableState<W> {
809    type Widget = W;
810    crate::state_accessors!();
811    fn init_state(self: Handle<Self>, app: &mut App) {
812        let widget = self.widget(app).clone();
813        let recognizer = widget.create_recognizer(
814            app,
815            Rc::new(move |app, position| self.start_drag(app, position)),
816        );
817        app.get_mut(self).recognizer = Some(recognizer);
818    }
819
820    fn dispose(self: Handle<Self>, app: &mut App) {
821        self.dispose_recognizer_if_inactive(app);
822    }
823
824    fn did_change_dependencies(self: Handle<Self>, app: &mut App) {
825        let context = self.context(app);
826        let settings = MediaQuery::maybe_gesture_settings_of(app, context);
827        app.get(self)
828            .recognizer
829            .handle()
830            .unwrap()
831            .set_gesture_settings(app, settings);
832    }
833
834    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
835        let widget = self.widget(app).draggable();
836        let can_drag = widget
837            .max_simultaneous_drags
838            .is_none_or(|max| app.get(self).active_count < max);
839        let show_child = app.get(self).active_count == 0 || widget.child_when_dragging.is_none();
840        let mut listener = crate::Listener::new()
841            .behavior(widget.hit_test_behavior)
842            .child(if show_child {
843                widget.child.clone()
844            } else {
845                widget.child_when_dragging.clone().unwrap()
846            });
847        if can_drag {
848            listener =
849                listener.on_pointer_down(Rc::new(move |app, event| self.route_pointer(app, event)));
850        }
851        listener.into_widget()
852    }
853}
854
855/// Details when a draggable is dropped, including acceptance, velocity, and offset.
856#[derive(Clone, Copy, Debug)]
857pub struct DraggableDetails {
858    /// Determines whether the `DragTarget` accepted this draggable.
859    pub was_accepted: bool,
860
861    /// The velocity at which the pointer was moving when the specific pointer
862    /// event occurred on the draggable.
863    pub velocity: Velocity,
864
865    /// The global position when the specific pointer event occurred on
866    /// the draggable.
867    pub offset: Offset,
868}
869
870/// The data and global position at which a pointer event occurred on a drag target.
871pub struct DragTargetDetails<T> {
872    /// The data that was dropped onto this `DragTarget`.
873    pub data: Rc<T>,
874
875    /// The global position when the specific pointer event occurred on
876    /// the draggable.
877    pub offset: Offset,
878}
879
880impl<T> Clone for DragTargetDetails<T> {
881    fn clone(&self) -> Self {
882        Self {
883            data: self.data.clone(),
884            offset: self.offset,
885        }
886    }
887}
888
889/// A widget that receives data when a Draggable is dropped over it.
890pub struct DragTarget<T: 'static> {
891    /// Identity of this target in its parent's child list.
892    pub key: Option<KeyRef>,
893
894    /// Builds the target using all current accepted and rejected drag data.
895    pub builder: DragTargetBuilder<T>,
896
897    /// Legacy data-only acceptance predicate; mutually exclusive with the detailed predicate.
898    pub on_will_accept: Option<DragTargetWillAccept<T>>,
899
900    /// Determines whether to accept an entering drag, including its position.
901    pub on_will_accept_with_details: Option<DragTargetWillAcceptWithDetails<T>>,
902
903    /// Called when non-null data is dropped on this target.
904    pub on_accept: Option<DragTargetAccept<T>>,
905
906    /// Called when non-null data is dropped, including its position.
907    pub on_accept_with_details: Option<DragTargetAcceptWithDetails<T>>,
908
909    /// Called when a drag leaves this target.
910    pub on_leave: Option<DragTargetLeave<T>>,
911
912    /// Called when non-null drag data moves within this target.
913    pub on_move: Option<DragTargetMove<T>>,
914
915    /// Defaults to translucent so targets behind rejected targets can receive a drag.
916    pub hit_test_behavior: HitTestBehavior,
917}
918
919impl<T: 'static> fmt::Debug for DragTarget<T> {
920    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
921        f.debug_struct("DragTarget").finish_non_exhaustive()
922    }
923}
924
925impl<T: 'static> DragTarget<T> {
926    /// Creates a target whose presentation reflects the current candidate and rejected data.
927    pub fn new(
928        builder: impl Fn(
929            &mut App,
930            BuildContext,
931            Vec<Option<Rc<T>>>,
932            Vec<Option<Rc<dyn Any>>>,
933        ) -> WidgetRef
934        + 'static,
935    ) -> Self {
936        Self {
937            key: None,
938            builder: Rc::new(builder),
939            on_will_accept: None,
940            on_will_accept_with_details: None,
941            on_accept: None,
942            on_accept_with_details: None,
943            on_leave: None,
944            on_move: None,
945            hit_test_behavior: HitTestBehavior::Translucent,
946        }
947    }
948
949    /// Sets the widget identity.
950    pub fn key(mut self, value: KeyRef) -> Self {
951        self.key = Some(value);
952        self
953    }
954
955    /// Sets the legacy data-only acceptance predicate.
956    pub fn on_will_accept(mut self, value: DragTargetWillAccept<T>) -> Self {
957        self.on_will_accept = Some(value);
958        self
959    }
960
961    /// Sets the predicate for accepting an entering drag.
962    pub fn on_will_accept_with_details(
963        mut self,
964        value: DragTargetWillAcceptWithDetails<T>,
965    ) -> Self {
966        self.on_will_accept_with_details = Some(value);
967        self
968    }
969
970    /// Sets the callback for dropped non-null data.
971    pub fn on_accept(mut self, value: DragTargetAccept<T>) -> Self {
972        self.on_accept = Some(value);
973        self
974    }
975
976    /// Sets the callback for a drop's data and global position.
977    pub fn on_accept_with_details(mut self, value: DragTargetAcceptWithDetails<T>) -> Self {
978        self.on_accept_with_details = Some(value);
979        self
980    }
981
982    /// Sets the callback for a drag leaving the target.
983    pub fn on_leave(mut self, value: DragTargetLeave<T>) -> Self {
984        self.on_leave = Some(value);
985        self
986    }
987
988    /// Sets the callback for movement within the target.
989    pub fn on_move(mut self, value: DragTargetMove<T>) -> Self {
990        self.on_move = Some(value);
991        self
992    }
993
994    /// Sets how the target participates in hit testing.
995    pub fn hit_test_behavior(mut self, value: HitTestBehavior) -> Self {
996        self.hit_test_behavior = value;
997        self
998    }
999}
1000
1001impl<T: 'static> StatefulWidget for DragTarget<T> {
1002    type State = DragTargetState<T>;
1003
1004    fn key(&self) -> Option<&KeyRef> {
1005        self.key.as_ref()
1006    }
1007
1008    fn create_state(&self) -> Self::State {
1009        debug_assert!(
1010            self.on_will_accept.is_none() || self.on_will_accept_with_details.is_none(),
1011            "Don't pass both acceptance callbacks"
1012        );
1013        DragTargetState {
1014            state: StateData::new(),
1015            candidate_avatars: Vec::new(),
1016            rejected_avatars: Vec::new(),
1017        }
1018    }
1019}
1020
1021/// The candidate and rejected avatars currently hovering over one target.
1022pub struct DragTargetState<T: 'static> {
1023    /// Native widget lifecycle and element association.
1024    state: StateData<DragTarget<T>>,
1025
1026    /// Avatars whose data this target accepted on entry.
1027    candidate_avatars: Vec<Ref<DragAvatar>>,
1028
1029    /// Avatars whose data this target rejected on entry.
1030    rejected_avatars: Vec<Ref<DragAvatar>>,
1031}
1032
1033/// Erases the target's data type while retaining its normal mounted-state checks.
1034trait DragTargetHandler {
1035    fn id(&self) -> HandleId;
1036
1037    fn is_expected_data_type(&self, data: &Option<Rc<dyn Any>>) -> bool;
1038
1039    fn did_enter(&self, app: &mut App, avatar: Handle<DragAvatar>) -> bool;
1040
1041    fn did_leave(&self, app: &mut App, avatar: Handle<DragAvatar>);
1042
1043    fn did_drop(&self, app: &mut App, avatar: Handle<DragAvatar>);
1044
1045    fn did_move(&self, app: &mut App, avatar: Handle<DragAvatar>);
1046}
1047
1048/// Keeps a target alive while hit testing and active drags hold its metadata.
1049struct DragTargetMetadata {
1050    /// Erased target callbacks stored in the render metadata, which keep the target's state.
1051    handler: Rc<dyn DragTargetHandler>,
1052}
1053
1054impl<T: 'static> DragTargetHandler for Ref<DragTargetState<T>> {
1055    fn id(&self) -> HandleId {
1056        self.into()
1057    }
1058
1059    fn is_expected_data_type(&self, data: &Option<Rc<dyn Any>>) -> bool {
1060        data.as_ref().is_none_or(|data| data.is::<T>())
1061    }
1062
1063    fn did_enter(&self, app: &mut App, avatar: Handle<DragAvatar>) -> bool {
1064        debug_assert!(
1065            !app.get(self)
1066                .candidate_avatars
1067                .iter()
1068                .any(|kept| kept == avatar)
1069        );
1070        debug_assert!(
1071            !app.get(self)
1072                .rejected_avatars
1073                .iter()
1074                .any(|kept| kept == avatar)
1075        );
1076        let data = app
1077            .get(avatar)
1078            .data
1079            .clone()
1080            .map(|data| data.downcast::<T>().unwrap());
1081        let widget = self.widget(app);
1082        let accepted = match (
1083            widget.on_will_accept.clone(),
1084            widget.on_will_accept_with_details.clone(),
1085        ) {
1086            (None, None) => true,
1087            (Some(callback), _) => callback(app, data.clone()),
1088            (_, Some(callback)) => data.is_some_and(|data| {
1089                callback(
1090                    app,
1091                    DragTargetDetails {
1092                        data,
1093                        offset: app.get(avatar).last_offset.unwrap(),
1094                    },
1095                )
1096            }),
1097        };
1098        let kept = avatar.keep(app);
1099        self.set_state(app, |state| {
1100            if accepted {
1101                state.candidate_avatars.push(kept)
1102            } else {
1103                state.rejected_avatars.push(kept)
1104            }
1105        });
1106        accepted
1107    }
1108
1109    fn did_leave(&self, app: &mut App, avatar: Handle<DragAvatar>) {
1110        if !self.mounted(app) {
1111            return;
1112        }
1113        self.set_state(app, |state| {
1114            state
1115                .candidate_avatars
1116                .retain(|candidate| candidate != avatar);
1117            state
1118                .rejected_avatars
1119                .retain(|candidate| candidate != avatar);
1120        });
1121        if let Some(callback) = self.widget(app).on_leave.clone() {
1122            let data = app
1123                .get(avatar)
1124                .data
1125                .clone()
1126                .map(|data| data.downcast::<T>().unwrap());
1127            callback(app, data);
1128        }
1129    }
1130
1131    fn did_drop(&self, app: &mut App, avatar: Handle<DragAvatar>) {
1132        debug_assert!(
1133            app.get(self)
1134                .candidate_avatars
1135                .iter()
1136                .any(|kept| kept == avatar)
1137        );
1138        if !self.mounted(app) {
1139            return;
1140        }
1141        self.set_state(app, |state| {
1142            state
1143                .candidate_avatars
1144                .retain(|candidate| candidate != avatar)
1145        });
1146        if let Some(data) = app.get(avatar).data.clone() {
1147            let data = data.downcast::<T>().unwrap();
1148            if let Some(callback) = self.widget(app).on_accept.clone() {
1149                callback(app, data.clone());
1150            }
1151            if let Some(callback) = self.widget(app).on_accept_with_details.clone() {
1152                callback(
1153                    app,
1154                    DragTargetDetails {
1155                        data,
1156                        offset: app.get(avatar).last_offset.unwrap(),
1157                    },
1158                );
1159            }
1160        }
1161    }
1162
1163    fn did_move(&self, app: &mut App, avatar: Handle<DragAvatar>) {
1164        if !self.mounted(app) {
1165            return;
1166        }
1167        if let Some(data) = app.get(avatar).data.clone()
1168            && let Some(callback) = self.widget(app).on_move.clone()
1169        {
1170            callback(
1171                app,
1172                DragTargetDetails {
1173                    data: data.downcast::<T>().unwrap(),
1174                    offset: app.get(avatar).last_offset.unwrap(),
1175                },
1176            );
1177        }
1178    }
1179}
1180
1181impl<T: 'static> State for DragTargetState<T> {
1182    type Widget = DragTarget<T>;
1183    crate::state_accessors!();
1184
1185    fn build(self: Handle<Self>, app: &mut App, context: BuildContext) -> WidgetRef {
1186        let state = app.get(self);
1187        let candidates = state
1188            .candidate_avatars
1189            .iter()
1190            .map(|avatar| {
1191                app.get(avatar)
1192                    .data
1193                    .clone()
1194                    .map(|data| data.downcast::<T>().unwrap())
1195            })
1196            .collect();
1197        let rejected = state
1198            .rejected_avatars
1199            .iter()
1200            .map(|avatar| app.get(avatar).data.clone())
1201            .collect();
1202        let builder = self.widget(app).builder.clone();
1203        let child = builder(app, context, candidates, rejected);
1204        MetaData::new()
1205            .meta_data(Rc::new(DragTargetMetadata {
1206                handler: Rc::new(self.keep(app)),
1207            }))
1208            .behavior(self.widget(app).hit_test_behavior)
1209            .child(child)
1210            .into_widget()
1211    }
1212}
1213
1214/// Whether the pointer ended normally or the drag was canceled.
1215#[derive(Clone, Copy, PartialEq, Eq)]
1216enum DragEndKind {
1217    Dropped,
1218    Canceled,
1219}
1220
1221/// Reports the final velocity, feedback offset and target acceptance.
1222type OnDragEnd = Rc<dyn Fn(&mut App, Velocity, Offset, bool)>;
1223
1224/// The feedback overlay and target path for one active pointer.
1225struct DragAvatar {
1226    /// The data carried by this draggable.
1227    data: Option<Rc<dyn Any>>,
1228
1229    /// The axis restricting drag motion, if specified.
1230    axis: Option<Axis>,
1231
1232    /// Pickup offset used to anchor feedback to the pointer.
1233    drag_start_point: Offset,
1234
1235    /// The widget displayed beneath the pointer during the drag.
1236    feedback: WidgetRef,
1237
1238    /// Offset used when hit testing to find drag targets.
1239    feedback_offset: Offset,
1240
1241    /// Called after an update changes the drag position.
1242    on_drag_update: DragUpdateCallback,
1243
1244    /// Reports the restricted velocity, final offset and acceptance.
1245    on_drag_end: OnDragEnd,
1246
1247    /// Overlay into which the feedback entry is inserted.
1248    overlay_state: Handle<OverlayState>,
1249
1250    /// Whether feedback is excluded from the semantics tree.
1251    ignoring_feedback_semantics: bool,
1252
1253    /// Whether feedback is excluded from pointer hit testing.
1254    ignoring_feedback_pointer: bool,
1255
1256    /// View used to hit test the global drag position.
1257    view_id: ViewId,
1258
1259    /// First entered target currently accepting this avatar.
1260    active_target: Option<Rc<DragTargetMetadata>>,
1261
1262    /// Targets whose metadata appeared in the previous hit test.
1263    entered_targets: Vec<Rc<DragTargetMetadata>>,
1264
1265    /// Current global pointer position, restricted to the configured axis.
1266    position: Offset,
1267
1268    /// Last global feedback offset after subtracting the pickup anchor.
1269    last_offset: Option<Offset>,
1270
1271    /// Feedback origin in the overlay’s coordinate system.
1272    overlay_offset: Offset,
1273
1274    /// Overlay entry retained until the drag finishes.
1275    entry: Option<Ref<OverlayEntry>>,
1276}
1277
1278impl DragAvatar {
1279    /// Inserts feedback into the overlay and hit-tests the initial pointer position.
1280    #[allow(clippy::too_many_arguments)]
1281    fn new(
1282        app: &mut App,
1283        overlay_state: Handle<OverlayState>,
1284        data: Option<Rc<dyn Any>>,
1285        axis: Option<Axis>,
1286        initial_position: Offset,
1287        drag_start_point: Offset,
1288        feedback: WidgetRef,
1289        feedback_offset: Offset,
1290        ignoring_feedback_semantics: bool,
1291        ignoring_feedback_pointer: bool,
1292        view_id: ViewId,
1293        on_drag_update: DragUpdateCallback,
1294        on_drag_end: OnDragEnd,
1295    ) -> Ref<Self> {
1296        let avatar = app.create(Self {
1297            data,
1298            axis,
1299            drag_start_point,
1300            feedback,
1301            feedback_offset,
1302            on_drag_update,
1303            on_drag_end,
1304            overlay_state,
1305            ignoring_feedback_semantics,
1306            ignoring_feedback_pointer,
1307            view_id,
1308            active_target: None,
1309            entered_targets: Vec::new(),
1310            position: initial_position,
1311            last_offset: None,
1312            overlay_offset: Offset::ZERO,
1313            entry: None,
1314        });
1315        // Dart's `_entry` builds with a tear-off of the avatar, which keeps it while the entry is
1316        // in the overlay: the ring the entry and this builder make is cut when `finish_drag`
1317        // takes the entry.
1318        let kept = avatar.clone();
1319        let entry = OverlayEntry::new(
1320            app,
1321            Rc::new(move |app, context| kept.build(app, context)),
1322            false,
1323            false,
1324            false,
1325        );
1326        app.get_mut(&avatar).entry = Some(entry.clone());
1327        overlay_state.insert(app, entry, None, None);
1328        avatar.update_drag(app, initial_position);
1329        avatar
1330    }
1331
1332    /// Updates overlay coordinates, then enters, leaves and moves targets in hit-test order.
1333    fn update_drag(self: Handle<Self>, app: &mut App, global_position: Offset) {
1334        let state = app.get(self);
1335        let (overlay, anchor, feedback_offset, view_id) = (
1336            state.overlay_state,
1337            state.drag_start_point,
1338            state.feedback_offset,
1339            state.view_id,
1340        );
1341        app.get_mut(self).last_offset = Some(global_position - anchor);
1342        if overlay.mounted(app) {
1343            let render_box = overlay
1344                .context(app)
1345                .find_render_object(app)
1346                .unwrap()
1347                .as_box()
1348                .unwrap();
1349            app.get_mut(self).overlay_offset =
1350                render_box.global_to_local(app, global_position, None) - anchor;
1351            app.get(self).entry.handle().unwrap().mark_needs_build(app);
1352        }
1353        let mut result = HitTestResult::new();
1354        GestureBinding::instance(app).hit_test_in_view(
1355            app,
1356            &mut result,
1357            global_position + feedback_offset,
1358            view_id,
1359        );
1360        let mut targets = Vec::new();
1361        for entry in result.path() {
1362            let Some(hit) = (entry.target() as &dyn Any).downcast_ref::<BoxHitTestEntry>() else {
1363                continue;
1364            };
1365            let Some(render) = hit.target().as_object().downcast::<RenderMetaData>(app) else {
1366                continue;
1367            };
1368            let Some(metadata) = render
1369                .meta_data(app)
1370                .and_then(|value| value.downcast::<DragTargetMetadata>().ok())
1371            else {
1372                continue;
1373            };
1374            if metadata.handler.is_expected_data_type(&app.get(self).data) {
1375                targets.push(metadata);
1376            }
1377        }
1378        let state = app.get(self);
1379        let lists_match = !state.entered_targets.is_empty()
1380            && targets.len() >= state.entered_targets.len()
1381            && targets
1382                .iter()
1383                .zip(&state.entered_targets)
1384                .all(|(a, b)| a.handler.id() == b.handler.id());
1385        if lists_match
1386            && (state.active_target.is_some() || targets.len() == state.entered_targets.len())
1387        {
1388            for target in state.entered_targets.clone() {
1389                target.handler.did_move(app, self);
1390            }
1391            return;
1392        }
1393        self.leave_all_entered(app);
1394        let mut active = None;
1395        for target in targets {
1396            app.get_mut(self).entered_targets.push(target.clone());
1397            if target.handler.did_enter(app, self) {
1398                active = Some(target);
1399                break;
1400            }
1401        }
1402        for target in app.get(self).entered_targets.clone() {
1403            target.handler.did_move(app, self);
1404        }
1405        app.get_mut(self).active_target = active;
1406    }
1407
1408    /// Sends leave to every previously entered target before clearing the path.
1409    fn leave_all_entered(self: Handle<Self>, app: &mut App) {
1410        for target in app.get(self).entered_targets.clone() {
1411            target.handler.did_leave(app, self);
1412        }
1413        app.get_mut(self).entered_targets.clear();
1414    }
1415
1416    /// Drops on the active target, releases feedback, and reports the final outcome.
1417    fn finish_drag(self: Handle<Self>, app: &mut App, kind: DragEndKind, velocity: Velocity) {
1418        let target = app.get(self).active_target.clone();
1419        let mut accepted = false;
1420        if kind == DragEndKind::Dropped
1421            && let Some(target) = target
1422        {
1423            target.handler.did_drop(app, self);
1424            accepted = true;
1425            app.get_mut(self)
1426                .entered_targets
1427                .retain(|entry| entry.handler.id() != target.handler.id());
1428        }
1429        self.leave_all_entered(app);
1430        app.get_mut(self).active_target = None;
1431        let entry = app.get_mut(self).entry.take().unwrap();
1432        entry.remove(app);
1433        entry.dispose(app);
1434        let callback = app.get(self).on_drag_end.clone();
1435        callback(app, velocity, app.get(self).last_offset.unwrap(), accepted);
1436    }
1437
1438    /// Positions feedback in overlay coordinates.
1439    fn build(self: Handle<Self>, app: &mut App, _context: BuildContext) -> WidgetRef {
1440        let state = app.get(self);
1441        Positioned::new(
1442            ExcludeSemantics::new()
1443                .excluding(state.ignoring_feedback_semantics)
1444                .child(
1445                    IgnorePointer::new()
1446                        .ignoring(state.ignoring_feedback_pointer)
1447                        .child(state.feedback.clone()),
1448                ),
1449        )
1450        .left(state.overlay_offset.dx())
1451        .top(state.overlay_offset.dy())
1452        .into_widget()
1453    }
1454
1455    /// Restricts movement to the configured axis without changing hit-test coordinates.
1456    fn restrict_axis(self: Handle<Self>, app: &App, offset: Offset) -> Offset {
1457        match app.get(self).axis {
1458            Some(Axis::Horizontal) => Offset::new(offset.dx(), 0.0),
1459            Some(Axis::Vertical) => Offset::new(0.0, offset.dy()),
1460            None => offset,
1461        }
1462    }
1463}
1464
1465impl DragObject for DragAvatar {
1466    fn update(self: Handle<Self>, app: &mut App, details: DragUpdateDetails) {
1467        let old_position = app.get(self).position;
1468        let position = old_position + self.restrict_axis(app, details.delta);
1469        app.get_mut(self).position = position;
1470        self.update_drag(app, position);
1471        if position != old_position {
1472            let callback = app.get(self).on_drag_update.clone();
1473            callback(app, details);
1474        }
1475    }
1476
1477    fn end(self: Handle<Self>, app: &mut App, details: DragEndDetails) {
1478        let velocity = Velocity::new(self.restrict_axis(app, details.velocity.pixels_per_second));
1479        self.finish_drag(app, DragEndKind::Dropped, velocity);
1480    }
1481
1482    fn cancel(self: Handle<Self>, app: &mut App) {
1483        self.finish_drag(app, DragEndKind::Canceled, Velocity::ZERO);
1484    }
1485}