dioxus-dnd 3.1.0

Modular, accessible drag-and-drop for Dioxus: sortable lists, kanban boards, trees, grids, file drops, multi-select, touch support and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
//! The [`Draggable`] drag source: pointer and keyboard interaction, the
//! pointer-capture substitute, and the hierarchical keyboard navigation
//! that walks the zone registry.

use dioxus::html::MountedData;
use dioxus::prelude::*;

use std::rc::Rc;

use crate::core::hooks::{use_dnd, use_zone_registry, SettleFlag};
use crate::core::monitor::CancelReason;
use crate::core::session::DragCompletion;
use crate::core::state::DragStart;
use crate::core::strings::use_dnd_strings;
use crate::core::types::{
    effective_effect, Direction, DragId, DragMode, DragSessionId, DropEffect, Point, PointerKind,
    Rect, TouchSense, ZoneId,
};
use crate::core::world::{use_joined_window, WorldHit};
use crate::core::{
    platform, transition_with, ActivationConstraint, ActivationPolicy, Activator, GestureEffect,
    GestureEvent, GesturePhase, Promotion,
};

use super::delivery::{
    deliver_drop, drop_query, resolve_drag_hover, resolve_drag_target, DropCompletion, SettleRoute,
    RELEASE_RECOVERY_MOVES,
};
use super::merge_style_invariant_last;
use super::pointer::{pointer_client, primary_press, touch_style, HoldTimer};
use super::ActivatorContext;

/// Internal: which hierarchical move an arrow key requested.
#[derive(Debug, Clone, Copy, PartialEq)]
enum NavKey {
    Next,
    Prev,
    Descend,
    Ascend,
}

/// Map an arrow key to a hierarchical move, honoring layout direction:
/// horizontal arrows mirror under RTL (the WAI-ARIA tree convention), so
/// "into" is always the arrow pointing along reading order. Pure, for
/// testability.
fn nav_key(key: &Key, dir: Direction) -> Option<NavKey> {
    Some(match (key, dir) {
        (Key::ArrowDown, _) => NavKey::Next,
        (Key::ArrowUp, _) => NavKey::Prev,
        (Key::ArrowRight, Direction::Ltr) | (Key::ArrowLeft, Direction::Rtl) => NavKey::Descend,
        (Key::ArrowLeft, Direction::Ltr) | (Key::ArrowRight, Direction::Rtl) => NavKey::Ascend,
        _ => return None,
    })
}

fn keyboard_drop_points(rect: Option<Rect>) -> (Point, Point) {
    match rect {
        Some(r) => {
            let client = r.center();
            (client, client - r.origin())
        }
        None => (Point::default(), Point::default()),
    }
}

fn finish_pointer_source<T: Clone + 'static>(
    membership: Option<crate::core::world::JoinedWindow<T>>,
    dnd: &mut crate::core::state::DndContext<T>,
    session: DragSessionId,
    completion: DragCompletion,
) -> bool {
    match membership {
        Some(joined) => joined.world.finish_session(session, completion),
        None if completion.dropped() => dnd.finish_source(session, true),
        None => {
            let DragCompletion::Cancelled(reason) = completion else {
                unreachable!("dropped completion handled above")
            };
            dnd.cancel_session(session, reason)
        }
    }
}

/// Wraps its children in a focusable pointer/keyboard drag source and pushes
/// `payload` into the shared context on drag start.
///
/// Any extra attributes (`class`, `style`, `id`…) are forwarded to the div.
///
/// While this element's payload is in flight the div carries
/// `data-dragging="true"`, and `data-disabled="true"` when `disabled` -
/// both are *absent* otherwise, so presence-based selectors (CSS
/// `[data-dragging]`, Tailwind `data-dragging:opacity-50`) work directly.
#[component]
pub fn Draggable<T: Clone + PartialEq + 'static>(
    /// The value delivered to whichever `DropZone` receives this drag.
    payload: T,
    /// Stable source identity. Auto-generated once per mounted draggable.
    #[props(default)]
    drag_id: Option<DragId>,
    /// The zone this item currently lives in (reported in `DropOutcome::from`).
    #[props(default)]
    zone: Option<ZoneId>,
    /// Drop effect. Defaults to `Move`.
    #[props(default)]
    effect: DropEffect,
    /// Disable dragging without unmounting.
    #[props(default)]
    disabled: bool,
    /// Movement in CSS px before a pointer press becomes a drag.
    #[props(default = 8.0)]
    threshold: f64,
    /// Composable activation policy. When omitted, `threshold` retains the
    /// 3.x distance behavior.
    #[props(default)]
    activation: Option<ActivationPolicy>,
    /// How a finger shares this element with native scrolling.
    /// [`TouchSense::Auto`] (default) keeps vertical swipes scrolling the
    /// page and picks up on a short hold or a sideways pull;
    /// [`TouchSense::Immediate`] owns every touch from the first pixel.
    /// Mouse drags are identical under both; pens follow the finger rules.
    #[props(default)]
    touch: TouchSense,
    /// Human label used in screen-reader announcements ("Picked up {label}").
    #[props(default)]
    label: Option<String>,
    /// Fired when a drag begins.
    #[props(default)]
    on_drag_start: Option<EventHandler<()>>,
    /// Fired when the drag ends; `true` if a zone consumed the payload,
    /// `false` if it was cancelled.
    #[props(default)]
    on_drag_end: Option<EventHandler<bool>>,
    #[props(extends = div, extends = GlobalAttributes)] attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    let auto_drag_id = use_hook(DragId::auto);
    let drag_id = drag_id.unwrap_or(auto_drag_id);
    rsx! {
        for keyed_drag_id in [drag_id] {
            DraggableInstance::<T> {
                key: "{keyed_drag_id.0}",
                payload: payload.clone(),
                drag_id: keyed_drag_id,
                zone,
                effect,
                disabled,
                threshold,
                activation: activation.clone(),
                touch,
                label: label.clone(),
                on_drag_start,
                on_drag_end,
                attributes: attributes.clone(),
                {children.clone()}
            }
        }
    }
}

#[component]
fn DraggableInstance<T: Clone + PartialEq + 'static>(
    payload: T,
    drag_id: DragId,
    zone: Option<ZoneId>,
    effect: DropEffect,
    disabled: bool,
    threshold: f64,
    activation: Option<ActivationPolicy>,
    touch: TouchSense,
    label: Option<String>,
    on_drag_start: Option<EventHandler<()>>,
    on_drag_end: Option<EventHandler<bool>>,
    attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    let mut dnd = use_dnd::<T>();
    let registry = use_zone_registry::<T>();
    let settle_flag = try_use_context::<SettleFlag<T>>();
    // Multi-window: when the provider joined a `DndWorld`, pointer moves
    // and releases resolve across every joined window. `None` (the normal
    // single-window case) leaves every path below exactly as it was.
    let membership = use_joined_window::<T>();
    // Everything the keyboard path voices, localizable through context.
    let strings = use_dnd_strings();
    let requested_activation = activation.unwrap_or(ActivationPolicy::surface(
        ActivationConstraint::Distance(threshold),
    ));
    let activation = use_memo(use_reactive!(|requested_activation| requested_activation));
    let activation_threshold = activation
        .peek()
        .constraint
        .distance()
        .unwrap_or(f64::INFINITY);
    let activation_delays = activation.peek().constraint.delays();
    let has_activation_delay = !activation_delays.is_empty();
    let mut handle_pointer = use_signal(|| None::<i32>);
    let mut handle_keyboard = use_signal(|| false);
    use_context_provider(|| ActivatorContext {
        pointer: handle_pointer,
        keyboard: handle_keyboard,
    });
    // Separate clones for the two closures that need the payload.
    let kb_payload = payload.clone();
    let pointer_payload = payload.clone();
    let attr_payload = payload.clone();
    let kb_label = label.clone();
    // For claiming a keyboard drop's focus restoration on mount.
    let mount_payload = payload.clone();
    let mut phase = use_signal(|| GesturePhase::Idle);
    // Generation of the pointer drag currently owned by this source. The
    // shared completion slot carries its callback across VirtualDom/window
    // boundaries; this local copy guards delayed measurement tasks.
    let mut session = use_signal(|| None::<DragSessionId>);
    // Did native pointer capture engage for the current press? When it
    // did, events retarget to this element and no capture substitute is
    // needed (or wanted - see the layer below).
    let mut captured = use_signal(|| false);
    // Consecutive empty-held moves seen mid-drag (lost-release debounce).
    let mut empty_held_moves = use_signal(|| 0u8);
    // Some(pid) while a touch press under `Auto` waits on its hold timer;
    // doubles as the timer element's render condition.
    let mut hold_pid = use_signal(|| None::<i32>);
    // Greatest distance reached during this press. Delay tolerances describe
    // the whole gesture, so moving out and back in must not revalidate one.
    let mut press_max_travel = use_signal(|| 0.0_f64);
    // The initiating press's device kind, recorded into the drag state at
    // promotion so host-side glue can tell captured pointers from blind ones.
    let mut press_kind = use_signal(PointerKind::default);
    let mut step = move |event: GestureEvent, threshold: f64| -> GestureEffect {
        let promotion = if touch == TouchSense::Auto && *press_kind.peek() != PointerKind::Mouse {
            Promotion::HoldOrSideways
        } else {
            Promotion::Distance
        };
        let (next, fx) = transition_with(*phase.peek(), event, threshold, promotion);
        phase.set(next);
        // Any exit from Pressed retires the pending hold - the drag began,
        // the press tapped out, or a vertical pull yielded to the scroll.
        if hold_pid.peek().is_some() && !matches!(next, GesturePhase::Pressed { .. }) {
            hold_pid.set(None);
        }
        fx
    };
    let mut node = use_signal(|| None::<Rc<MountedData>>);
    let mut press_offset = use_signal(Point::default);
    // The element's rect, measured at press time - so a promotion can hand
    // the ghost its size synchronously. Measuring at Begin instead left the
    // `match_source` overlay blank for the measurement roundtrip (~a few
    // frames), a visible pop-in at every pickup.
    let mut press_rect = use_signal(|| None::<Rect>);
    let mut press_measure_generation = use_signal(|| 0u64);
    let mut mods = use_signal(Modifiers::empty);
    let mut attributes = attributes;
    super::protect_attributes(
        &mut attributes,
        &[
            "data-dragging",
            "data-disabled",
            "onmounted",
            "onpointerdown",
            "onpointermove",
            "onpointerup",
            "onpointercancel",
            "onlostpointercapture",
            "ontouchmove",
            "oncontextmenu",
            "tabindex",
            "role",
            "aria-roledescription",
            "onkeydown",
        ],
    );
    let style = merge_style_invariant_last(
        &mut attributes,
        touch_style(touch),
        &["touch-action", "user-select", "-webkit-user-select"],
    );

    // Every pointer end path (DOM, host bridge, cancel, or source unmount)
    // consumes the same shared callback. It runs in this source runtime and
    // resets the gesture before notifying the application.
    let source_completion = use_callback(move |dropped: bool| {
        let pointer_id = match *phase.peek() {
            GesturePhase::Dragging { pointer_id, .. } => Some(pointer_id),
            _ => None,
        };
        phase.set(GesturePhase::Idle);
        session.set(None);
        if let Some(pointer_id) = pointer_id {
            if let Some(n) = node.peek().clone() {
                platform::release_pointer(&n, pointer_id);
            }
        }
        captured.set(false);
        empty_held_moves.set(0);
        hold_pid.set(None);
        press_max_travel.set(0.0);
        press_rect.set(None);
        press_measure_generation += 1;
        press_kind.set(PointerKind::default());
        mods.set(Modifiers::empty());
        if let Some(h) = &on_drag_end {
            h.call(dropped);
        }
    });
    use_drop(move || {
        let Some(id) = *session.peek() else {
            return;
        };
        finish_pointer_source(
            membership,
            &mut dnd,
            id,
            DragCompletion::Cancelled(CancelReason::SourceUnmounted),
        );
    });

    // Begin is reachable from two places - a pointer-move promotion and the
    // hold timer's alarm - so the sequence lives in one callback.
    let begin_drag = use_callback(move |at: Point| {
        let source_rect = *press_rect.peek();
        let id = dnd.start_tracked_with_metadata(
            drag_id,
            DragStart::new(pointer_payload.clone(), at)
                .with_source(zone)
                .with_grab(*press_offset.peek())
                .with_effect(effect)
                .with_pointer_kind(*press_kind.peek())
                .with_source_rect(source_rect),
            source_completion,
        );
        if !dnd.is_session(id) {
            return;
        }
        dnd.set_proposed_effect(effective_effect(effect, *mods.peek()));
        session.set(Some(id));
        // Dress a size-matched ghost immediately from the press-time
        // measurement; fall back to measuring now only if the press's
        // measurement hasn't landed yet (a press promoted within a frame).
        if source_rect.is_none() {
            if let Some(m) = node.peek().clone() {
                let mut dnd = dnd;
                spawn(async move {
                    if let Ok(r) = m.get_client_rect().await {
                        if dnd.is_session(id) {
                            dnd.set_source_rect(Some(Rect::new(
                                r.origin.x,
                                r.origin.y,
                                r.size.width,
                                r.size.height,
                            )));
                        }
                    }
                });
            }
        }
        // A world drag anchors its coordinates to this window and needs
        // every joined window's rects fresh, not just this one's.
        match membership {
            Some(j) => {
                j.world.begin_from(j.key);
                j.world.update_modifiers(*mods.peek());
                j.world.refresh_all_rects();
            }
            None => registry.refresh_rects(),
        }
        if let Some(h) = &on_drag_start {
            h.call(());
        }
    });

    let mut deliver_to = move |target: ZoneId, point: Point, effect: DropEffect| -> bool {
        // Delivery may synchronously finish the source and run
        // `source_completion`, which clears this signal. Snapshot the token so
        // no `peek` guard remains borrowed across that callback boundary.
        let active_session = *session.peek();
        match membership {
            Some(joined) => deliver_drop(
                registry,
                &mut dnd,
                SettleRoute {
                    flag: settle_flag,
                    owner: Some((&joined.world, joined.key)),
                },
                DropCompletion::World {
                    world: &joined.world,
                    session: active_session,
                },
                target,
                point,
                effect,
            ),
            None => deliver_drop(
                registry,
                &mut dnd,
                SettleRoute {
                    flag: settle_flag,
                    owner: None,
                },
                match active_session {
                    Some(session) => DropCompletion::Local(session),
                    None => DropCompletion::None,
                },
                target,
                point,
                effect,
            ),
        }
    };

    let mut finish_drop = move |point: Point| {
        let Some(id) = *session.peek() else {
            return;
        };
        dnd.update_pointer(point);
        if !dnd.is_session(id) {
            return;
        }
        if let Some(joined) = membership {
            // Record an authoritative release point even when no final move
            // preceded it. Receiver intent and settle anchoring consume the
            // global projection updated by this lookup.
            let _ = joined.zone_under(point);
            joined.world.update_modifiers(*mods.peek());
        }
        let effect = effective_effect(effect, *mods.peek());
        dnd.set_proposed_effect(effect);
        // A release the world resolves into a FOREIGN window delivers
        // there: that window's registry and settle flag, coordinates in
        // its client px (including its own 48px snap, in its own CSS px).
        // Own-window and unresolved releases (no geometry, outside every
        // window) fall through to the classic path below, so
        // single-window behavior is untouched - origin-window snap
        // included.
        if let Some(j) = membership {
            if let Some((rec, local)) = j.foreign_window_under(point) {
                let mut dnd = dnd;
                spawn(async move {
                    if !dnd.is_session(id) || !j.world.is_drag_session(id) {
                        return;
                    }
                    // Resolve exact cached hits through the acceptance-aware
                    // path so a rejecting later registry record falls through.
                    // Only a miss pays for a fresh measurement + 48px snap.
                    let query = dnd
                        .payload()
                        .map(|payload| drop_query(&dnd, payload, effect));
                    let mut target = query.as_ref().and_then(|query| {
                        rec.registry
                            .resolve(query, local, j.world.active_rect_in(rec, local), 0.0)
                            .map(|(zone, _)| zone)
                    });
                    if target.is_none() {
                        rec.registry.measure_all().await;
                        if !dnd.is_session(id) || !j.world.is_drag_session(id) {
                            return;
                        }
                        let query = dnd
                            .payload()
                            .map(|payload| drop_query(&dnd, payload, effect));
                        target = query.as_ref().and_then(|query| {
                            rec.registry
                                .resolve(
                                    query,
                                    local,
                                    j.world.active_rect_in(rec, local),
                                    rec.registry.release_policy().recovery_radius,
                                )
                                .map(|(zone, _)| zone)
                        });
                    }
                    if !dnd.is_session(id) || !j.world.is_drag_session(id) {
                        return;
                    }
                    let dropped = target
                        .map(|t| {
                            deliver_drop(
                                rec.registry,
                                &mut dnd,
                                SettleRoute {
                                    flag: Some(rec.settle),
                                    owner: Some((&j.world, rec.key)),
                                },
                                DropCompletion::World {
                                    world: &j.world,
                                    session: Some(id),
                                },
                                t,
                                local,
                                effect,
                            )
                        })
                        .unwrap_or(false);
                    if !dropped {
                        finish_pointer_source(
                            Some(j),
                            &mut dnd,
                            id,
                            DragCompletion::Cancelled(CancelReason::NoTarget),
                        );
                    }
                });
                return;
            }
        }
        let cached_target = resolve_drag_target(registry, &dnd, point, effect, 0.0);
        if let Some(target) = cached_target {
            if deliver_to(target, point, effect) {
                return;
            }
        }
        spawn(async move {
            registry.measure_all().await;
            if !dnd.is_session(id)
                || membership.is_some_and(|joined| !joined.world.is_drag_session(id))
            {
                return;
            }
            let target = resolve_drag_target(
                registry,
                &dnd,
                point,
                effect,
                registry.release_policy().recovery_radius,
            );
            let dropped = match target {
                Some(t) => deliver_to(t, point, effect),
                None => false,
            };
            if !dropped {
                finish_pointer_source(
                    membership,
                    &mut dnd,
                    id,
                    DragCompletion::Cancelled(CancelReason::NoTarget),
                );
            }
        });
    };

    rsx! {
        div {
            style: style,
            "data-dragging": if dnd.dragging()
                && (dnd.drag_id() == Some(drag_id)
                    || (!dnd.has_explicit_drag_id()
                        && dnd.payload().as_ref() == Some(&attr_payload)))
            { "true" },
            "data-disabled": if disabled { "true" },
            onmounted: move |evt: Event<MountedData>| {
                let m: Rc<MountedData> = evt.data();
                node.set(Some(m.clone()));
                // Focus continuity for keyboard drops: if this mount IS the
                // just-dropped payload landing in its new place, take the
                // focus the browser dropped when the source unmounted.
                if !disabled && dnd.claim_refocus(&mount_payload) {
                    spawn(async move {
                        let _ = m.set_focus(true).await;
                    });
                }
            },
            onpointerdown: move |evt: PointerEvent| {
                let handle_match = *handle_pointer.peek() == Some(evt.pointer_id());
                // Consume the one-event capability even when this press is
                // disabled or non-primary. A rejected handle event must not
                // authorize a later mouse press that reuses the pointer id.
                handle_pointer.set(None);
                if disabled || !primary_press(&evt) {
                    return;
                }
                if activation.peek().constraint.is_manual()
                    || matches!(activation.peek().activator, Activator::Manual)
                    || (matches!(activation.peek().activator, Activator::Handle) && !handle_match)
                {
                    return;
                }
                // A prior release may still be awaiting its async snap
                // measurement; its Up already moved the machine out of
                // Dragging, so retire that stale generation before the
                // machine sees a new Down. Gated on the phase: a session
                // with the machine still in Dragging is a LIVE drag, and a
                // second primary press (a mouse click during a touch drag,
                // a pen tap during a mouse drag) must not steal it -
                // (Dragging, Down) is deliberately inert.
                if !matches!(*phase.peek(), GesturePhase::Dragging { .. }) {
                    // Copy out of the peek BEFORE finishing: an `if let` on
                    // `*session.peek()` keeps the read guard alive through
                    // the body (edition 2021 scrutinee temporaries), and
                    // `finish_pointer_source` synchronously runs the
                    // completion callback, whose `session.set(None)` then
                    // aborts the process from an unwind-proof Win32 callback
                    // (AlreadyBorrowed; observed live on Windows 11).
                    let stale = *session.peek();
                    if let Some(id) = stale {
                        finish_pointer_source(
                            membership,
                            &mut dnd,
                            id,
                            DragCompletion::Cancelled(CancelReason::Replaced),
                        );
                    }
                }
                empty_held_moves.set(0);
                press_max_travel.set(0.0);
                mods.set(evt.modifiers());
                // Suppress the press's default actions - the same line the
                // sortable rows carry. The one that matters: `tabindex=0`
                // makes this div mouse-focusable as a browser side effect,
                // and that stray focus outlives the drop (the model mutates,
                // nodes get reused, and the ring can surface on an unrelated
                // item). Keyboard focus via Tab is untouched, and clicks
                // on inner controls still fire (`click` is not a
                // compatibility mouse event).
                evt.prevent_default();
                evt.stop_propagation();
                captured.set(match node.peek().clone() {
                    Some(n) => platform::capture_pointer(&n, evt.pointer_id()),
                    None => false,
                });
                let o = evt.element_coordinates();
                press_offset.set(Point::new(o.x, o.y));
                press_kind.set(PointerKind::from_pointer_type(&evt.pointer_type()));
                // Measure at press so a later promotion can size the ghost
                // without waiting on a roundtrip (see `press_rect`).
                press_rect.set(None);
                press_measure_generation += 1;
                let measurement_generation = *press_measure_generation.peek();
                if let Some(m) = node.peek().clone() {
                    spawn(async move {
                        if let Ok(r) = m.get_client_rect().await {
                            if *press_measure_generation.peek() != measurement_generation {
                                return;
                            }
                            press_rect.set(Some(Rect::new(
                                r.origin.x,
                                r.origin.y,
                                r.size.width,
                                r.size.height,
                            )));
                        }
                    });
                }
                // Defense in depth: tracked completion resets the source
                // immediately for host-ended drags. If custom integration
                // bypassed that path, do not let a stale Dragging phase eat
                // this press ((Dragging, Down) is deliberately inert).
                if !dnd.dragging() && matches!(*phase.peek(), GesturePhase::Dragging { .. }) {
                    let _ = step(GestureEvent::Cancel, activation_threshold);
                }
                let pid = evt.pointer_id();
                let _ = step(
                    GestureEvent::Down { at: pointer_client(&evt), pointer_id: pid },
                    activation_threshold,
                );
                // Arm the long-press clock: fingers (and pens) under `Auto`
                // promote on hold-or-sideways; mice promote on travel alone.
                let legacy_touch_hold = !has_activation_delay
                    && touch == TouchSense::Auto
                    && evt.pointer_type() != "mouse";
                if (has_activation_delay || legacy_touch_hold)
                    && matches!(*phase.peek(), GesturePhase::Pressed { pointer_id, .. } if pointer_id == pid)
                {
                    hold_pid.set(Some(pid));
                }
            },
            onpointermove: move |evt: PointerEvent| {
                let at = pointer_client(&evt);
                if let GesturePhase::Pressed { origin, pointer_id } = *phase.peek() {
                    if pointer_id == evt.pointer_id() {
                        let delta = at - origin;
                        let travel = delta.x.hypot(delta.y);
                        if travel > *press_max_travel.peek() {
                            press_max_travel.set(travel);
                        }
                        if activation
                            .peek()
                            .constraint
                            .exceeded_delay_tolerance(*press_max_travel.peek(), 0.0)
                        {
                            hold_pid.set(None);
                            if activation.peek().constraint.distance().is_none() {
                                let _ = step(GestureEvent::Cancel, activation_threshold);
                                return;
                            }
                        }
                    }
                }
                mods.set(evt.modifiers());
                if let Some(joined) = membership {
                    joined.world.update_modifiers(evt.modifiers());
                }
                // Lost-release recovery, debounced: only a RUN of empty-
                // held moves is believed (see RELEASE_RECOVERY_MOVES).
                let released = if matches!(*phase.peek(), GesturePhase::Dragging { .. })
                    && evt.held_buttons().is_empty()
                {
                    let streak = empty_held_moves.peek().saturating_add(1);
                    empty_held_moves.set(streak);
                    streak >= RELEASE_RECOVERY_MOVES
                } else {
                    if *empty_held_moves.peek() != 0 {
                        empty_held_moves.set(0);
                    }
                    false
                };
                let event = if released {
                    if let Some(n) = node.peek().clone() {
                        platform::release_pointer(&n, evt.pointer_id());
                    }
                    GestureEvent::Up { at, pointer_id: evt.pointer_id() }
                } else {
                    GestureEvent::Move { at, pointer_id: evt.pointer_id() }
                };
                match step(event, activation_threshold) {
                    GestureEffect::Begin { at, .. } => begin_drag.call(at),
                    GestureEffect::Track { at } => {
                        let Some(id) = *session.peek() else {
                            return;
                        };
                        dnd.update_pointer(at);
                        if !dnd.is_session(id) {
                            return;
                        }
                        let proposed = effective_effect(effect, *mods.peek());
                        dnd.set_proposed_effect(proposed);
                        let query = dnd
                            .payload()
                            .map(|payload| drop_query(&dnd, payload, proposed));
                        // World-resolved hits are authoritative even when
                        // zoneless: a foreign window IN FRONT of one of our
                        // zones must not let the covered zone light up.
                        match membership {
                            Some(joined) => match query
                                .as_ref()
                                .map(|query| joined.zone_under_query(at, query))
                                .unwrap_or(WorldHit::Unresolved)
                            {
                                WorldHit::Zone(location) => joined.enter(location),
                                WorldHit::Window => joined.clear_hover(),
                                WorldHit::Unresolved => match resolve_drag_hover(
                                    registry, &dnd, at, proposed,
                                ) {
                                    Some(zone) => joined.enter(joined.location(zone)),
                                    None => joined.clear_hover(),
                                },
                            },
                            None => match resolve_drag_hover(registry, &dnd, at, proposed) {
                                Some(zone) => dnd.enter(zone),
                                None => {
                                    if let Some(over) = dnd.over() {
                                        dnd.leave(over);
                                    }
                                }
                            },
                        }
                    }
                    GestureEffect::Drop { at: point } => finish_drop(point),
                    _ => {}
                }
            },
            onpointerup: move |evt: PointerEvent| {
                if let Some(n) = node.peek().clone() {
                    platform::release_pointer(&n, evt.pointer_id());
                }
                mods.set(evt.modifiers());
                if let Some(joined) = membership {
                    joined.world.update_modifiers(evt.modifiers());
                }
                let GestureEffect::Drop { at: point } = step(
                    GestureEvent::Up { at: pointer_client(&evt), pointer_id: evt.pointer_id() },
                    activation_threshold,
                ) else {
                    return;
                };
                finish_drop(point);
            },
            onpointercancel: move |evt: PointerEvent| {
                if let Some(n) = node.peek().clone() {
                    platform::release_pointer(&n, evt.pointer_id());
                }
                if step(GestureEvent::Cancel, activation_threshold) == GestureEffect::Abort {
                    // Copied out of the peek before finishing - same borrow
                    // discipline as the pointerdown retire above.
                    let cancelled = *session.peek();
                    if let Some(id) = cancelled {
                        finish_pointer_source(
                            membership,
                            &mut dnd,
                            id,
                            DragCompletion::Cancelled(CancelReason::PointerCancelled),
                        );
                    }
                }
            },
            onlostpointercapture: move |_| {
                if step(GestureEvent::Cancel, activation_threshold) == GestureEffect::Abort {
                    // Copied out of the peek before finishing - same borrow
                    // discipline as the pointerdown retire above.
                    let lost = *session.peek();
                    if let Some(id) = lost {
                        finish_pointer_source(
                            membership,
                            &mut dnd,
                            id,
                            DragCompletion::Cancelled(CancelReason::PointerCancelled),
                        );
                    }
                }
            },
            // A promoted drag owns the touch: cancel its moves so the
            // browser can't start a pan mid-drag. (`touch-action` is only
            // consulted at gesture start, so `pan-y` alone can't do this.)
            // dioxus-web's delegated listener is non-passive - see the
            // touch-sensor browser spec.
            ontouchmove: move |evt: TouchEvent| {
                if matches!(*phase.peek(), GesturePhase::Dragging { .. }) {
                    evt.prevent_default();
                }
            },
            // Android pops a context menu on touch long-press (the iOS
            // callout is already off via touch_style); mid-gesture that
            // would tear the hold or the drag. Idle presses keep the menu.
            oncontextmenu: move |evt: Event<MouseData>| {
                if !matches!(*phase.peek(), GesturePhase::Idle) {
                    evt.prevent_default();
                }
            },
            // --- keyboard interaction ---------------------------------
            // Space/Enter picks the item up, arrow keys cycle acceptable
            // zones, Space/Enter drops, Escape cancels. Announcements go
            // through the context; render `a11y::LiveRegion` to voice them.
            tabindex: if disabled || !matches!(activation.peek().activator, Activator::Surface) { -1_i64 } else { 0 },
            role: if matches!(activation.peek().activator, Activator::Surface) { Some("button") } else { None },
            aria_roledescription: "draggable",
            onkeydown: move |evt: KeyboardEvent| {
                if disabled {
                    return;
                }
                let from_handle = *handle_keyboard.peek();
                handle_keyboard.set(false);
                if activation.peek().constraint.is_manual()
                    || matches!(activation.peek().activator, Activator::Manual)
                    || (matches!(activation.peek().activator, Activator::Handle) && !from_handle)
                {
                    return;
                }
                let registry = registry;
                let key = evt.key();
                let is_activate = matches!(key, Key::Enter)
                    || matches!(&key, Key::Character(c) if c == " ");
                let kb_drag = dnd.dragging() && dnd.mode() == DragMode::Keyboard;

                if !dnd.dragging() && is_activate {
                    evt.prevent_default();
                    dnd.start_with_id(
                        drag_id,
                        DragStart::new(kb_payload.clone(), Point::default())
                            .with_source(zone)
                            .with_effect(effect)
                            .with_mode(DragMode::Keyboard),
                    );
                    if !dnd.dragging()
                        || dnd.drag_id() != Some(drag_id)
                        || dnd.mode() != DragMode::Keyboard
                    {
                        return;
                    }
                    if let Some(joined) = membership {
                        joined.world.begin_from(joined.key);
                    }
                    // Measure zones so arrow-key order can follow visual
                    // (top-to-bottom, left-to-right) layout.
                    registry.refresh_rects();
                    let name = kb_label.clone().unwrap_or_else(|| (strings.item)());
                    dnd.announce((strings.picked_up)(&name));
                    if let Some(h) = &on_drag_start {
                        h.call(());
                    }
                    return;
                }

                if !kb_drag {
                    return;
                }

                // Hierarchical navigation (WAI-ARIA tree convention):
                // Up/Down cycle siblings at the current level; the arrow
                // along reading order descends into the hovered zone's
                // children; the opposite one ascends to its parent (both
                // mirror under RTL). In flat apps (no nesting) they fall
                // back to next/previous, preserving the simple behavior.
                let nav = nav_key(&key, registry.direction());
                if let (Some(nav), Some(p)) = (nav, dnd.payload()) {
                    evt.prevent_default();
                    let over = dnd.over();
                    let query = drop_query(&dnd, p, effect);
                    let next = match nav {
                        NavKey::Next => registry.step_sibling_query(over, &query, 1),
                        NavKey::Prev => registry.step_sibling_query(over, &query, -1),
                        NavKey::Descend => over
                            .and_then(|z| registry.first_child_query(z, &query))
                            .or_else(|| registry.step_sibling_query(over, &query, 1)),
                        NavKey::Ascend => over
                            .and_then(|z| registry.ascend(z))
                            .or_else(|| registry.step_sibling_query(over, &query, -1)),
                    };
                    if let Some(next) = next {
                        match membership {
                            Some(joined) => joined.enter(joined.location(next)),
                            None => dnd.enter(next),
                        }
                        let record = registry.get(next);
                        let name = record
                            .as_ref()
                            .and_then(|z| z.label.clone())
                            .unwrap_or_else(|| (strings.zone)(next.0));
                        let inside = record
                            .as_ref()
                            .and_then(|z| z.parent)
                            .and_then(|pid| registry.get(pid))
                            .and_then(|pz| pz.label);
                        match inside {
                            Some(parent) => dnd.announce((strings.over_inside)(&name, &parent)),
                            None => dnd.announce((strings.over)(&name)),
                        }
                    } else {
                        dnd.announce((strings.no_targets)());
                    }
                    return;
                }

                if is_activate {
                    evt.prevent_default();
                    // A custom source can enter() an id from another type's
                    // registry; falling back keeps Enter from dying silently.
                    let target = dnd.over().filter(|z| registry.contains(*z)).or_else(|| {
                        dnd.payload().and_then(|payload| {
                            let query = drop_query(&dnd, payload, effect);
                            registry.step_zone_query(None, &query, 1)
                        })
                    });
                    let Some(target) = target else {
                        dnd.announce((strings.no_target_selected)());
                        return;
                    };
                    if let Some(record) = registry.get(target) {
                        if let Some(payload) = dnd.payload() {
                            let (client, _) = keyboard_drop_points(registry.cached_rect(target));
                            let delivered = match membership {
                                Some(joined) => deliver_drop(
                                    registry,
                                    &mut dnd,
                                    SettleRoute {
                                        flag: settle_flag,
                                        owner: Some((&joined.world, joined.key)),
                                    },
                                    DropCompletion::World {
                                        world: &joined.world,
                                        session: None,
                                    },
                                    target,
                                    client,
                                    effect,
                                ),
                                None => deliver_drop(
                                    registry,
                                    &mut dnd,
                                    SettleRoute {
                                        flag: settle_flag,
                                        owner: None,
                                    },
                                    DropCompletion::None,
                                    target,
                                    client,
                                    effect,
                                ),
                            };
                            if !delivered {
                                dnd.announce((strings.no_target_selected)());
                                return;
                            }
                            // The drop re-mounts the moved item. Its new
                            // source claims this request and restores focus.
                            dnd.request_refocus(payload);
                            let name = record
                                .label
                                .unwrap_or_else(|| (strings.zone)(target.0));
                            dnd.announce((strings.dropped_in)(&name));
                            if let Some(h) = &on_drag_end {
                                h.call(true);
                            }
                        }
                    }
                    return;
                }

                if matches!(key, Key::Escape) {
                    evt.prevent_default();
                    if let Some(joined) = membership {
                        joined
                            .world
                            .finish_untracked(DragCompletion::Cancelled(CancelReason::User));
                    } else {
                        dnd.cancel();
                    }
                    dnd.announce((strings.cancelled)());
                    if let Some(h) = &on_drag_end {
                        h.call(false);
                    }
                }
            },
            ..attributes,
            // Pointer-capture SUBSTITUTE, rendered only when native capture
            // did not engage. With capture (the `web` feature), events
            // retarget to this element already - and the layer must not
            // exist, so the page's own hit-testing (`elementFromPoint`
            // introspection included) stays untouched. Without capture
            // (desktop webviews, web without the feature) nothing
            // retargets: the moment the cursor left this element mid-drag
            // the move stream died and the ghost froze. This full-viewport
            // child then owns every pointer event and lets it bubble to
            // the handlers above - no separate handlers, no renderer API.
            // Gated on the shared context too, so a drag completed from
            // outside this element (host-driven drop, another window's
            // delivery) can never leave a stale layer eating input.
            // (Being position: fixed, it is clipped by any transformed
            // ancestor - the standard containing-block caveat, shared with
            // the overlay.)
            if matches!(phase(), GesturePhase::Dragging { .. }) && dnd.dragging() && !captured() {
                div {
                    style: "position: fixed; inset: 0; z-index: 9998; touch-action: none;",
                    aria_hidden: true,
                }
            }
            // Armed only while a touch press waits under `Auto`; the alarm
            // promotes exactly like a threshold crossing, at the origin.
            if let Some(pid) = hold_pid() {
                if activation_delays.is_empty() {
                    HoldTimer {
                        pointer_id: pid,
                        delay_ms: super::pointer::HOLD_DELAY_MS,
                        on_hold: move |pid| {
                            if let GestureEffect::Begin { at, .. } =
                                step(GestureEvent::Hold { pointer_id: pid }, activation_threshold)
                            {
                                begin_drag.call(at);
                            }
                        },
                    }
                } else {
                    for (timer_index, (duration_ms, tolerance)) in
                        activation_delays.iter().copied().enumerate()
                    {
                        HoldTimer {
                            key: "{timer_index}-{duration_ms}",
                            pointer_id: pid,
                            delay_ms: duration_ms as f64,
                            on_hold: move |pid| {
                                if *press_max_travel.peek() <= tolerance {
                                    if let GestureEffect::Begin { at, .. } = step(
                                        GestureEvent::Hold { pointer_id: pid },
                                        activation_threshold,
                                    ) {
                                        begin_drag.call(at);
                                    }
                                }
                            },
                        }
                    }
                }
            }
            {children}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Horizontal arrows mirror under RTL: "descend into" is always the
    /// arrow pointing along reading order. Vertical arrows never mirror.
    #[test]
    fn nav_keys_mirror_under_rtl() {
        for dir in [Direction::Ltr, Direction::Rtl] {
            assert_eq!(nav_key(&Key::ArrowDown, dir), Some(NavKey::Next));
            assert_eq!(nav_key(&Key::ArrowUp, dir), Some(NavKey::Prev));
            assert_eq!(nav_key(&Key::Enter, dir), None);
        }
        assert_eq!(
            nav_key(&Key::ArrowRight, Direction::Ltr),
            Some(NavKey::Descend)
        );
        assert_eq!(
            nav_key(&Key::ArrowLeft, Direction::Ltr),
            Some(NavKey::Ascend)
        );
        assert_eq!(
            nav_key(&Key::ArrowRight, Direction::Rtl),
            Some(NavKey::Ascend)
        );
        assert_eq!(
            nav_key(&Key::ArrowLeft, Direction::Rtl),
            Some(NavKey::Descend)
        );
    }

    #[test]
    fn keyboard_drop_points_use_zone_center_and_element_offset() {
        let rect = Rect::new(40.0, 80.0, 200.0, 100.0);
        let (client, element) = keyboard_drop_points(Some(rect));

        assert_eq!(client, Point::new(140.0, 130.0));
        assert_eq!(element, Point::new(100.0, 50.0));
    }

    #[test]
    fn keyboard_drop_points_fall_back_to_origin_without_rect() {
        let (client, element) = keyboard_drop_points(None);

        assert_eq!(client, Point::default());
        assert_eq!(element, Point::default());
    }
}