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
#![doc = include_str!("../docs/api/testing.md")]

use std::any::{Any, TypeId};
use std::cell::RefCell;
use std::collections::HashMap;

use dioxus::prelude::*;

use crate::core::components::{
    deliver_drop, drop_query, resolve_drag_hover, resolve_drag_target, DropCompletion, SettleRoute,
};
use crate::core::hooks::SettleFlag;
use crate::core::monitor::CancelReason;
use crate::core::world::{JoinedWindow, WorldHit, WorldMembership};
use crate::core::{
    use_dnd, use_zone_registry, DndContext, DragCompletion, DropEffect, Point, Rect, WindowKey,
    ZoneId, ZoneRegistry,
};

thread_local! {
    /// Handles captured by [`DragSimProbe`], keyed by payload type. One
    /// slot per type per thread: the most recently mounted probe wins,
    /// which is exactly right for one `VirtualDom` per test.
    static SIMS: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::new());
}

/// Captures a [`DragSim`] for the enclosing provider. Mount one inside the
/// `DndProvider<T>` of your *test* app (it renders nothing), then retrieve
/// the handle with [`drag_sim`] after `rebuild_in_place`.
#[component]
pub fn DragSimProbe<T: Clone + PartialEq + 'static>(
    /// Internal marker; never set this.
    #[props(default)]
    phantom: std::marker::PhantomData<T>,
) -> Element {
    let _ = phantom;
    let completions = use_signal(Vec::<bool>::new);
    let completion = use_callback(move |dropped| {
        let mut completions = completions;
        completions.write().push(dropped);
    });
    let sim = DragSim {
        dnd: use_dnd::<T>(),
        registry: use_zone_registry::<T>(),
        settle: try_use_context::<SettleFlag<T>>(),
        membership: try_use_context::<WorldMembership<T>>().and_then(|m| m.0),
        completion,
        completions,
    };
    use_hook(move || {
        SIMS.with_borrow_mut(|m| {
            m.insert(TypeId::of::<T>(), Box::new(sim));
        });
    });
    rsx! {}
}

/// The handle the most recent [`DragSimProbe<T>`] captured.
///
/// # Panics
/// Panics when no probe for `T` has mounted - add `DragSimProbe::<T> {}`
/// inside the provider and `rebuild_in_place` first.
pub fn drag_sim<T: Clone + PartialEq + 'static>() -> DragSim<T> {
    SIMS.with_borrow(|m| {
        m.get(&TypeId::of::<T>())
            .and_then(|b| b.downcast_ref::<DragSim<T>>())
            .copied()
    })
    .expect("no DragSim captured: mount DragSimProbe::<T> inside the provider and rebuild first")
}

/// Headless driver for one provider's drag world. Every method takes the
/// `VirtualDom` so the underlying signal operations run inside its runtime;
/// call [`rerender`] between actions and markup assertions.
pub struct DragSim<T: Clone + 'static> {
    dnd: DndContext<T>,
    registry: ZoneRegistry<T>,
    settle: Option<SettleFlag<T>>,
    /// The provider's world membership, when it joined a `DndWorld` -
    /// moves and releases then resolve across windows, like the gesture.
    membership: Option<JoinedWindow<T>>,
    completion: Callback<bool>,
    completions: Signal<Vec<bool>>,
}

impl<T: Clone + 'static> Copy for DragSim<T> {}
impl<T: Clone + 'static> Clone for DragSim<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Clone + PartialEq + 'static> DragSim<T> {
    /// Give a zone its client rect - the headless stand-in for layout.
    ///
    /// # Panics
    /// Panics when no zone with this id is registered.
    pub fn place(&self, dom: &VirtualDom, zone: ZoneId, rect: Rect) {
        dom.in_runtime(|| {
            assert!(
                self.registry.contains(zone),
                "place: no zone {} registered",
                zone.0
            );
            let mut registry = self.registry;
            registry.set_rect(zone, rect);
        });
    }

    /// The key this sim's provider joined its world under, when it did.
    pub fn window_key(&self) -> Option<WindowKey> {
        self.membership.map(|j| j.key)
    }

    /// [`Self::place`] for a zone living in another joined window's
    /// registry - `rect` is in **that window's** client px.
    ///
    /// # Panics
    /// Panics when this sim's provider joined no world, the window is
    /// unknown, or the zone isn't registered there.
    pub fn place_in(&self, dom: &VirtualDom, window: WindowKey, zone: ZoneId, rect: Rect) {
        let world = self
            .membership
            .expect("place_in: this provider joined no DndWorld")
            .world;
        dom.in_runtime(|| {
            let rec = world
                .record(window)
                .unwrap_or_else(|| panic!("place_in: no window {} joined", window.0));
            assert!(
                rec.registry.contains(zone),
                "place_in: no zone {} in window {}",
                zone.0,
                window.0
            );
            let mut registry = rec.registry;
            registry.set_rect(zone, rect);
        });
    }

    /// Begin a pointer drag carrying `payload`, from no particular zone.
    pub fn pick_up(&mut self, dom: &VirtualDom, payload: T) {
        self.pick_up_from(dom, payload, None);
    }

    /// Begin a pointer drag, reporting `from` as the source zone
    /// (arrives in `DropOutcome::from`).
    pub fn pick_up_from(&mut self, dom: &VirtualDom, payload: T, from: Option<ZoneId>) {
        let mut dnd = self.dnd;
        let membership = self.membership;
        dom.in_runtime(|| {
            let session = dnd.start_tracked(
                payload,
                from,
                Point::default(),
                Point::default(),
                DropEffect::Move,
                self.completion,
            );
            // Like the gesture: a world drag anchors to this window.
            if dnd.is_session(session) {
                if let Some(j) = membership {
                    j.world.begin_from(j.key);
                }
            }
        });
    }

    /// Move the pointer: updates the tracked position and enters/leaves
    /// zones by hit-testing the placed rects - the same logic the pointer
    /// gesture runs per `pointermove`.
    pub fn move_to(&mut self, dom: &VirtualDom, point: Point) {
        let mut dnd = self.dnd;
        let registry = self.registry;
        let membership = self.membership;
        dom.in_runtime(|| {
            let session = dnd.active_session();
            dnd.update_pointer(point);
            if session.is_some_and(|session| !dnd.is_session(session)) {
                return;
            }
            let query = dnd
                .payload()
                .map(|payload| drop_query(&dnd, payload, dnd.effect()));
            // Same resolution order as the gesture: world hits (any
            // window) are authoritative, unresolved points fall back to
            // the local registry.
            match membership {
                Some(joined) => match query
                    .as_ref()
                    .map(|query| joined.zone_under_query(point, query))
                    .unwrap_or(WorldHit::Unresolved)
                {
                    WorldHit::Zone(location) => joined.enter(location),
                    WorldHit::Window => joined.clear_hover(),
                    WorldHit::Unresolved => {
                        match resolve_drag_hover(registry, &dnd, point, dnd.effect()) {
                            Some(zone) => joined.enter(joined.location(zone)),
                            None => joined.clear_hover(),
                        }
                    }
                },
                None => match resolve_drag_hover(registry, &dnd, point, dnd.effect()) {
                    Some(zone) => dnd.enter(zone),
                    None => {
                        if let Some(over) = dnd.over() {
                            dnd.leave(over);
                        }
                    }
                },
            }
        });
    }

    /// Release at the current pointer position. Returns the zone that
    /// received the drop, or `None` when the drag cancelled (no acceptable
    /// zone under the pointer or within the provider's configured recovery
    /// radius).
    pub fn release(&mut self, dom: &VirtualDom) -> Option<ZoneId> {
        self.release_as(dom, DropEffect::Move)
    }

    /// [`Self::release`] with an explicit effect - simulate the Ctrl-held
    /// copy drop with `DropEffect::Copy`.
    pub fn release_as(&mut self, dom: &VirtualDom, effect: DropEffect) -> Option<ZoneId> {
        let mut dnd = self.dnd;
        let registry = self.registry;
        let settle = self.settle;
        let membership = self.membership;
        dom.in_runtime(|| {
            let point = dnd.pointer();
            let session = dnd.active_session();
            // A release the world resolves into a foreign window delivers
            // there, mirroring the gesture (the snap runs in the target
            // window's own CSS px). Headless rects are placed, so the
            // gesture's pre-snap re-measure is skipped as documented.
            if let Some(j) = membership {
                let _ = j.zone_under(point);
                if let Some((rec, local)) = j.foreign_window_under(point) {
                    let target = dnd.payload().and_then(|payload| {
                        let query = drop_query(&dnd, payload, effect);
                        rec.registry
                            .resolve(
                                &query,
                                local,
                                j.world.active_rect_in(rec, local),
                                rec.registry.release_policy().recovery_radius,
                            )
                            .map(|(zone, _)| zone)
                    });
                    let delivered = target
                        .filter(|t| {
                            deliver_drop(
                                rec.registry,
                                &mut dnd,
                                SettleRoute {
                                    flag: Some(rec.settle),
                                    owner: Some((&j.world, rec.key)),
                                },
                                DropCompletion::World {
                                    world: &j.world,
                                    session,
                                },
                                *t,
                                local,
                                effect,
                            )
                        })
                        .is_some();
                    if !delivered {
                        match session {
                            Some(session) => {
                                j.world.finish_session(
                                    session,
                                    DragCompletion::Cancelled(CancelReason::NoTarget),
                                );
                            }
                            None => j.world.finish_untracked(DragCompletion::Cancelled(
                                CancelReason::NoTarget,
                            )),
                        }
                        return None;
                    }
                    return target;
                }
            }
            let target = resolve_drag_target(
                registry,
                &dnd,
                point,
                effect,
                registry.release_policy().recovery_radius,
            );
            let delivered = target
                .filter(|t| match membership {
                    Some(j) => deliver_drop(
                        registry,
                        &mut dnd,
                        SettleRoute {
                            flag: settle,
                            owner: Some((&j.world, j.key)),
                        },
                        DropCompletion::World {
                            world: &j.world,
                            session,
                        },
                        *t,
                        point,
                        effect,
                    ),
                    None => deliver_drop(
                        registry,
                        &mut dnd,
                        SettleRoute {
                            flag: settle,
                            owner: None,
                        },
                        match session {
                            Some(session) => DropCompletion::Local(session),
                            None => DropCompletion::None,
                        },
                        *t,
                        point,
                        effect,
                    ),
                })
                .is_some();
            if !delivered {
                match membership {
                    Some(j) => match session {
                        Some(session) => {
                            j.world.finish_session(
                                session,
                                DragCompletion::Cancelled(CancelReason::NoTarget),
                            );
                        }
                        None => j
                            .world
                            .finish_untracked(DragCompletion::Cancelled(CancelReason::NoTarget)),
                    },
                    None => match session {
                        Some(session) => {
                            dnd.cancel_session(session, CancelReason::NoTarget);
                        }
                        None => dnd.cancel_with_reason(CancelReason::NoTarget),
                    },
                }
                return None;
            }
            target
        })
    }

    /// Abort the drag, as Escape or a pointer cancel would.
    pub fn cancel(&mut self, dom: &VirtualDom) {
        let mut dnd = self.dnd;
        let membership = self.membership;
        dom.in_runtime(|| {
            let session = dnd.active_session();
            match membership {
                Some(j) => match session {
                    Some(session) => {
                        j.world
                            .finish_session(session, DragCompletion::Cancelled(CancelReason::User));
                    }
                    None => {
                        j.world
                            .finish_untracked(DragCompletion::Cancelled(CancelReason::User));
                    }
                },
                None => match session {
                    Some(session) => {
                        dnd.cancel_session(session, CancelReason::User);
                    }
                    None => dnd.cancel(),
                },
            }
        });
    }

    /// Exactly-once source completion results observed by the simulated
    /// source (`true` for delivered, `false` for cancelled).
    pub fn completions(&self, dom: &VirtualDom) -> Vec<bool> {
        dom.in_runtime(|| self.completions.read().clone())
    }

    /// The zone currently hovered.
    pub fn over(&self, dom: &VirtualDom) -> Option<ZoneId> {
        dom.in_runtime(|| self.dnd.over())
    }

    /// Is a drag in flight?
    pub fn dragging(&self, dom: &VirtualDom) -> bool {
        dom.in_runtime(|| self.dnd.dragging())
    }

    /// The in-flight payload, if any.
    pub fn payload(&self, dom: &VirtualDom) -> Option<T> {
        dom.in_runtime(|| self.dnd.payload())
    }

    /// The latest screen-reader announcement.
    pub fn announcement(&self, dom: &VirtualDom) -> String {
        dom.in_runtime(|| self.dnd.announcement())
    }
}

/// Flush pending reactivity so the tree reflects the simulated state -
/// call between driver actions and markup assertions
/// (`dioxus_ssr::render`).
pub fn rerender(dom: &mut VirtualDom) {
    dom.process_events();
    dom.render_immediate(&mut dioxus::core::NoOpMutations);
}

/// One whole pointer drag: pick `payload` up (from `from`), glide through
/// `path`, release at its last point, re-rendering between steps so zone
/// reactions run just as they would live. Returns the receiving zone, or
/// `None` when the drag cancelled. Needs a mounted [`DragSimProbe<T>`];
/// an empty `path` releases at the pickup point.
pub fn simulate_drag<T: Clone + PartialEq + 'static>(
    dom: &mut VirtualDom,
    payload: T,
    from: Option<ZoneId>,
    path: &[Point],
) -> Option<ZoneId> {
    let mut sim = drag_sim::<T>();
    sim.pick_up_from(dom, payload, from);
    rerender(dom);
    for p in path {
        sim.move_to(dom, *p);
        rerender(dom);
    }
    let delivered = sim.release(dom);
    rerender(dom);
    delivered
}