dioxus-dnd 0.6.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
//! Ready-made components over the shared drag context.
//!
//! ```rust,ignore
//! rsx! {
//!     DndProvider::<Card> {
//!         Draggable::<Card> { payload: card.clone(), "Drag me" }
//!         DropZone::<Card> {
//!             on_drop: move |outcome: DropOutcome<Card>| { /* ... */ },
//!             "Drop here"
//!         }
//!     }
//! }
//! ```

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

use std::rc::Rc;

use super::hooks::{
    client_point, element_point, use_dnd, use_dnd_provider, use_zone_id, use_zone_registry,
};
use super::registry::ZoneRecord;

/// Context marker a `DropZone` provides so zones nested inside it can
/// discover their parent — powering hierarchical keyboard traversal with no
/// configuration.
#[derive(Clone, Copy, PartialEq)]
pub struct ParentZone(pub ZoneId);

/// Internal: which hierarchical move an arrow key requested.
#[derive(Clone, Copy)]
enum NavKey {
    Next,
    Prev,
    Descend,
    Ascend,
}
use super::types::{effective_effect, DragMode, DropEffect, DropOutcome, Point, ZoneId};

/// Provides a `DndContext<T>` to its children.
#[component]
pub fn DndProvider<T: Clone + PartialEq + 'static>(
    /// Internal marker; never set this.
    #[props(default)]
    phantom: std::marker::PhantomData<T>,
    children: Element,
) -> Element {
    let _ = phantom;
    use_dnd_provider::<T>();
    rsx! {
        {children}
    }
}

/// Wraps its children in a `div[draggable]` and pushes `payload` into the
/// shared context on drag start.
///
/// Any extra attributes (`class`, `style`, `id`…) are forwarded to the div.
#[component]
pub fn Draggable<T: Clone + PartialEq + 'static>(
    /// The value delivered to whichever `DropZone` receives this drag.
    payload: T,
    /// The zone this item currently lives in (reported in `DropOutcome::from`).
    #[props(default)]
    zone: Option<ZoneId>,
    /// HTML5 drop effect. Defaults to `Move`.
    #[props(default)]
    effect: DropEffect,
    /// Disable dragging without unmounting.
    #[props(default)]
    disabled: bool,
    /// 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 mut dnd = use_dnd::<T>();
    let registry = use_zone_registry::<T>();
    // Separate clones for the two closures that need the payload.
    let kb_payload = payload.clone();
    let kb_label = label.clone();

    rsx! {
        div {
            draggable: !disabled,
            ondragstart: move |evt: DragEvent| {
                if disabled {
                    return;
                }
                // Nested draggables: the innermost one owns the drag.
                evt.stop_propagation();
                let dt = evt.data_transfer();
                // Firefox refuses to start a drag unless *some* data is set.
                let _ = dt.set_data("text/plain", "dioxus-dnd");
                dt.set_effect_allowed(effect.as_str());
                dnd.start(
                    payload.clone(),
                    zone,
                    client_point(&evt),
                    element_point(&evt),
                    effect,
                    DragMode::Pointer,
                );
                if let Some(h) = &on_drag_start {
                    h.call(());
                }
            },
            ondrag: move |evt: DragEvent| {
                // Keeps DragOverlay tracking the pointer. Coordinates can be
                // (0,0) on some platforms; update_pointer filters those.
                dnd.update_pointer(client_point(&evt));
            },
            ondragend: move |_| {
                // If a DropZone consumed the payload, the state is already
                // idle — that's how we know the drop landed.
                let dropped = !dnd.dragging();
                dnd.cancel();
                if let Some(h) = &on_drag_end {
                    h.call(dropped);
                }
            },
            // --- 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 { -1_i64 } else { 0 },
            role: "button",
            aria_roledescription: "draggable",
            onkeydown: move |evt: KeyboardEvent| {
                if disabled {
                    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(
                        kb_payload.clone(),
                        zone,
                        Point::default(),
                        Point::default(),
                        effect,
                        DragMode::Keyboard,
                    );
                    // 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(|| "item".to_string());
                    dnd.announce(format!(
                        "Picked up {name}. Use arrow keys to choose a drop target,                          Enter to drop, Escape to cancel."
                    ));
                    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; Right
                // descends into the hovered zone's children; Left ascends
                // to its parent. In flat apps (no nesting) Right/Left fall
                // back to next/previous, preserving the simple behavior.
                let nav = match key {
                    Key::ArrowDown => Some(NavKey::Next),
                    Key::ArrowUp => Some(NavKey::Prev),
                    Key::ArrowRight => Some(NavKey::Descend),
                    Key::ArrowLeft => Some(NavKey::Ascend),
                    _ => None,
                };
                if let (Some(nav), Some(p)) = (nav, dnd.payload()) {
                    evt.prevent_default();
                    let over = dnd.over();
                    let next = match nav {
                        NavKey::Next => registry.step_sibling(over, &p, 1),
                        NavKey::Prev => registry.step_sibling(over, &p, -1),
                        NavKey::Descend => over
                            .and_then(|z| registry.first_child(z, &p))
                            .or_else(|| registry.step_sibling(over, &p, 1)),
                        NavKey::Ascend => over
                            .and_then(|z| registry.parent_of(z))
                            .or_else(|| registry.step_sibling(over, &p, -1)),
                    };
                    if let Some(next) = next {
                        dnd.enter(next);
                        let record = registry.get(next);
                        let name = record
                            .as_ref()
                            .and_then(|z| z.label.clone())
                            .unwrap_or_else(|| format!("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(format!("Over {name}, inside {parent}.")),
                            None => dnd.announce(format!("Over {name}.")),
                        }
                    } else {
                        dnd.announce("No drop targets available.");
                    }
                    return;
                }

                if is_activate {
                    evt.prevent_default();
                    let target = dnd.over().or_else(|| {
                        dnd.payload().and_then(|p| registry.step_zone(None, &p, 1))
                    });
                    let Some(target) = target else {
                        dnd.announce("No drop target selected.");
                        return;
                    };
                    if let Some(record) = registry.get(target) {
                        if let Some((p, from)) = dnd.take() {
                            let center = (*record.rect.peek())
                                .map(|r| r.center())
                                .unwrap_or_default();
                            record.on_drop.call(DropOutcome {
                                payload: p,
                                from,
                                to: target,
                                effect,
                                client: center,
                                element: Point::default(),
                            });
                            let name = record
                                .label
                                .unwrap_or_else(|| format!("zone {}", target.0));
                            dnd.announce(format!("Dropped in {name}."));
                            if let Some(h) = &on_drag_end {
                                h.call(true);
                            }
                        }
                    }
                    return;
                }

                if matches!(key, Key::Escape) {
                    evt.prevent_default();
                    dnd.cancel();
                    dnd.announce("Drag cancelled.");
                    if let Some(h) = &on_drag_end {
                        h.call(false);
                    }
                }
            },
            ..attributes,
            {children}
        }
    }
}

/// A region that accepts drags carrying `T`.
///
/// Handles the HTML5 boilerplate for you: `preventDefault` on dragover,
/// enter/leave depth counting (so child elements don't cause hover flicker),
/// and acceptance filtering.
#[component]
pub fn DropZone<T: Clone + PartialEq + 'static>(
    /// Stable identity for this zone. Auto-generated if omitted.
    #[props(default)]
    id: Option<ZoneId>,
    /// Human label for screen-reader announcements ("Over {label}").
    #[props(default)]
    label: Option<String>,
    /// Return `false` to reject a payload (zone won't highlight or accept it).
    #[props(default)]
    accepts: Option<Callback<T, bool>>,
    /// Fired on a successful drop.
    on_drop: EventHandler<DropOutcome<T>>,
    /// Fired when an acceptable drag first enters the zone.
    #[props(default)]
    on_enter: Option<EventHandler<T>>,
    /// Fired when the drag leaves the zone (or drops).
    #[props(default)]
    on_leave: Option<EventHandler<()>>,
    #[props(extends = div, extends = GlobalAttributes)] attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    let mut dnd = use_dnd::<T>();
    let mut registry = use_zone_registry::<T>();
    let auto_id = use_zone_id();
    let zone_id = id.unwrap_or(auto_id);
    // Nesting is automatic: a DropZone inside another discovers its parent
    // via context, and provides itself to zones deeper down.
    let parent = try_use_context::<ParentZone>().map(|p| p.0);
    use_context_provider(|| ParentZone(zone_id));
    // dragenter/dragleave fire for every child element; a depth counter turns
    // them into a single logical enter/leave pair.
    let mut depth = use_signal(|| 0u32);
    let mounted = use_signal(|| None::<Rc<MountedData>>);
    let rect = use_signal(|| None::<super::types::Rect>);

    // Register with the zone registry so keyboard navigation and pointer
    // hit-testing can find this zone. Callbacks are stable handles, so
    // registering once per mount is enough.
    use_hook(|| {
        registry.register(ZoneRecord {
            id: zone_id,
            parent,
            label: label.clone(),
            on_drop: Callback::new(move |o| on_drop.call(o)),
            accepts,
            mounted,
            rect,
        });
    });
    use_drop(move || {
        registry.unregister(zone_id);
    });
    // Keep the registered label in sync if the prop changes across renders.
    // Registry readers only `peek`, so this render-time write can't loop.
    registry.sync_label(zone_id, label.clone());

    let acceptable = move || -> bool {
        match dnd.payload() {
            Some(p) => accepts.map(|cb| cb.call(p)).unwrap_or(true),
            None => false,
        }
    };

    rsx! {
        div {
            onmounted: move |evt: Event<MountedData>| {
                let mut mounted = mounted;
                mounted.set(Some(evt.data()));
            },
            ondragover: move |evt: DragEvent| {
                if acceptable() {
                    // Without this, the browser never fires `drop`.
                    evt.prevent_default();
                    // Ctrl/Cmd = copy, Alt = link (file-manager convention).
                    let eff = effective_effect(dnd.effect(), evt.modifiers());
                    evt.data_transfer().set_drop_effect(eff.as_str());
                }
            },
            ondragenter: move |evt: DragEvent| {
                if !acceptable() {
                    return;
                }
                evt.prevent_default();
                let d = depth() + 1;
                depth.set(d);
                if d == 1 {
                    dnd.enter(zone_id);
                    if let (Some(h), Some(p)) = (&on_enter, dnd.payload()) {
                        h.call(p);
                    }
                }
            },
            ondragleave: move |_| {
                let d = depth().saturating_sub(1);
                depth.set(d);
                if d == 0 {
                    dnd.leave(zone_id);
                    if let Some(h) = &on_leave {
                        h.call(());
                    }
                }
            },
            ondrop: move |evt: DragEvent| {
                evt.prevent_default();
                depth.set(0);
                if !acceptable() {
                    return;
                }
                let client = client_point(&evt);
                let element = element_point(&evt);
                let effect = effective_effect(dnd.effect(), evt.modifiers());
                if let Some((payload, from)) = dnd.take() {
                    on_drop.call(DropOutcome {
                        payload,
                        from,
                        to: zone_id,
                        effect,
                        client,
                        element,
                    });
                    if let Some(h) = &on_leave {
                        h.call(());
                    }
                }
            },
            ..attributes,
            {children}
        }
    }
}

/// Renders its children pinned to the pointer while a drag is in flight —
/// a custom "ghost" that follows the cursor.
///
/// Note: pointer tracking relies on the `drag` event's coordinates, which a
/// few webviews report as (0,0). The overlay simply won't move there; treat
/// it as progressive enhancement.
#[component]
pub fn DragOverlay<T: Clone + PartialEq + 'static>(
    /// Internal marker; never set this.
    #[props(default)]
    phantom: std::marker::PhantomData<T>,
    children: Element,
) -> Element {
    let _ = phantom;
    let dnd = use_dnd::<T>();
    if !dnd.dragging() {
        return rsx! {};
    }
    let p = dnd.pointer() - dnd.grab();
    rsx! {
        div {
            style: "position: fixed; left: {p.x}px; top: {p.y}px; pointer-events: none; z-index: 9999;",
            {children}
        }
    }
}