dioxus-dnd 2.3.1

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
//! The zone registry: every mounted [`crate::core::DropZone`] records itself
//! here (id, label, drop callback, acceptance filter, and its mounted DOM
//! handle). Pointer drags hit-test against cached client rects; keyboard
//! navigation walks the zones in spatial order (top-to-bottom, left-to-right,
//! with unmeasured zones last in registration order).

use std::rc::Rc;

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

use super::types::{Direction, DropOutcome, Point, Rect, ZoneId};

/// One registered drop zone.
pub struct ZoneRecord<T: Clone + 'static> {
    pub id: ZoneId,
    /// The enclosing zone, when this zone is nested inside another
    /// `DropZone` (discovered automatically via context).
    pub parent: Option<ZoneId>,
    /// Human label used in screen-reader announcements.
    pub label: Option<String>,
    /// Delivers a completed drop to the zone's owner.
    pub on_drop: Callback<DropOutcome<T>>,
    /// The zone's acceptance filter, if any.
    pub accepts: Option<Callback<T, bool>>,
    /// The zone's mounted element, once available.
    pub mounted: Signal<Option<Rc<MountedData>>>,
    /// Cached client rect (refreshed via [`ZoneRegistry::refresh_rects`]).
    pub rect: Signal<Option<Rect>>,
}

impl<T: Clone + 'static> Clone for ZoneRecord<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            parent: self.parent,
            label: self.label.clone(),
            on_drop: self.on_drop,
            accepts: self.accepts,
            mounted: self.mounted,
            rect: self.rect,
        }
    }
}

impl<T: Clone + 'static> ZoneRecord<T> {
    /// Does this zone accept the payload?
    pub fn accepts_payload(&self, payload: &T) -> bool {
        match self.accepts {
            Some(cb) => cb.call(payload.clone()),
            None => true,
        }
    }
}

/// Registry of the currently mounted drop zones, in mount order.
pub struct ZoneRegistry<T: Clone + 'static> {
    zones: Signal<Vec<ZoneRecord<T>>>,
    /// Layout direction for spatial ordering (keyboard navigation).
    dir: Signal<Direction>,
}

impl<T: Clone + 'static> Copy for ZoneRegistry<T> {}
impl<T: Clone + 'static> Clone for ZoneRegistry<T> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: Clone + 'static> PartialEq for ZoneRegistry<T> {
    fn eq(&self, other: &Self) -> bool {
        self.zones == other.zones && self.dir == other.dir
    }
}

impl<T: Clone + 'static> ZoneRegistry<T> {
    /// Wrap an existing signal. Prefer [`crate::core::hooks::use_dnd_provider`].
    pub fn from_signal(zones: Signal<Vec<ZoneRecord<T>>>) -> Self {
        Self {
            zones,
            dir: Signal::new(Direction::default()),
        }
    }

    /// Layout direction spatial ordering follows.
    pub fn direction(&self) -> Direction {
        *self.dir.peek()
    }

    /// Set the layout direction (no-op if unchanged; safe to call every
    /// render). `DndProvider`'s `dir` prop calls this for you.
    pub fn set_direction(&mut self, dir: Direction) {
        if *self.dir.peek() != dir {
            self.dir.set(dir);
        }
    }

    /// Add (or replace, by id) a zone.
    pub fn register(&mut self, record: ZoneRecord<T>) {
        let mut zones = self.zones.write();
        if let Some(existing) = zones.iter_mut().find(|z| z.id == record.id) {
            *existing = record;
        } else {
            zones.push(record);
        }
    }

    /// Update a zone's label in place (no-op if unchanged or unknown).
    pub fn sync_label(&mut self, id: ZoneId, label: Option<String>) {
        let needs = self
            .zones
            .peek()
            .iter()
            .any(|z| z.id == id && z.label != label);
        if needs {
            if let Some(z) = self.zones.write().iter_mut().find(|z| z.id == id) {
                z.label = label;
            }
        }
    }

    /// Remove a zone (call when its component unmounts).
    pub fn unregister(&mut self, id: ZoneId) {
        self.zones.write().retain(|z| z.id != id);
    }

    /// Look up a zone by id.
    pub fn get(&self, id: ZoneId) -> Option<ZoneRecord<T>> {
        self.zones.peek().iter().find(|z| z.id == id).cloned()
    }

    /// Is a zone with this id registered *here*? The parent-zone context is
    /// shared across payload types, so a record's `parent` can name a zone
    /// living in another type's registry - check before navigating to one.
    pub fn contains(&self, id: ZoneId) -> bool {
        self.zones.peek().iter().any(|z| z.id == id)
    }

    /// The zone keyboard navigation should enter when ascending from
    /// `current`: its parent, but only when that parent is registered in
    /// this registry. A `DropZone<A>` nested inside a `DropZone<B>` records
    /// B's id as its parent, and entering an id this registry can't resolve
    /// would leave the drag hovering a zone that can never receive it.
    pub fn ascend(&self, current: ZoneId) -> Option<ZoneId> {
        self.parent_of(current).filter(|pid| self.contains(*pid))
    }

    /// All zones accepting `payload`, in registration order.
    pub fn acceptable(&self, payload: &T) -> Vec<ZoneRecord<T>> {
        self.zones
            .peek()
            .iter()
            .filter(|z| z.accepts_payload(payload))
            .cloned()
            .collect()
    }

    /// The next/previous zone (cyclic) relative to `current` among zones that
    /// accept `payload`. `step` is `+1` or `-1`.
    ///
    /// Order is **spatial** (top-to-bottom, then left-to-right) for zones
    /// with measured rects - call [`Self::refresh_rects`] first, as the
    /// built-in keyboard interaction does on pickup. Unmeasured zones keep
    /// registration order, after the measured ones.
    pub fn step_zone(&self, current: Option<ZoneId>, payload: &T, step: isize) -> Option<ZoneId> {
        let mut zones = self.acceptable(payload);
        spatial_sort(&mut zones, self.direction());
        let current_ix = current.and_then(|c| zones.iter().position(|z| z.id == c));
        cycle(zones.len(), current_ix, step).map(|ix| zones[ix].id)
    }

    /// The parent of a zone, if it's nested.
    pub fn parent_of(&self, id: ZoneId) -> Option<ZoneId> {
        self.zones.peek().iter().find(|z| z.id == id)?.parent
    }

    /// Zones directly inside `parent` (`None` = root level) that accept
    /// `payload`, in spatial order (top-to-bottom, left-to-right; unmeasured
    /// zones keep registration order at the end).
    pub fn children_of(&self, parent: Option<ZoneId>, payload: &T) -> Vec<ZoneRecord<T>> {
        let mut zones: Vec<_> = self
            .zones
            .peek()
            .iter()
            .filter(|z| z.parent == parent && z.accepts_payload(payload))
            .cloned()
            .collect();
        spatial_sort(&mut zones, self.direction());
        zones
    }

    /// Next/previous zone (cyclic) among the *siblings* of `current` -
    /// zones sharing its parent. With no `current`, cycles the root level.
    pub fn step_sibling(
        &self,
        current: Option<ZoneId>,
        payload: &T,
        step: isize,
    ) -> Option<ZoneId> {
        let parent = current.and_then(|c| self.parent_of(c));
        let siblings = self.children_of(parent, payload);
        let current_ix = current.and_then(|c| siblings.iter().position(|z| z.id == c));
        cycle(siblings.len(), current_ix, step).map(|ix| siblings[ix].id)
    }

    /// The first (spatially) acceptable zone nested inside `id`.
    pub fn first_child(&self, id: ZoneId, payload: &T) -> Option<ZoneId> {
        self.children_of(Some(id), payload).first().map(|z| z.id)
    }

    /// Topmost zone containing `point` (client coordinates), using cached
    /// rects - call [`Self::refresh_rects`] when a drag starts. Later-mounted
    /// zones win, approximating DOM paint order.
    pub fn hit_test(&self, point: Point) -> Option<ZoneId> {
        self.zones
            .peek()
            .iter()
            .rev()
            .find(|z| (*z.rect.peek()).map(|r| r.contains(point)).unwrap_or(false))
            .map(|z| z.id)
    }

    /// Like [`Self::hit_test`], but acceptance-aware: it returns the topmost
    /// zone that both contains the point **and** accepts `payload`, and when no
    /// such zone contains the point, falls back to the acceptable zone whose
    /// center is nearest - within `max_distance` CSS px. Skipping zones that
    /// reject the payload lets a drop land on an accepting zone sitting *under*
    /// a rejecting (or decorative) one, and is friendlier for imprecise (touch)
    /// drops that land in the gutter between zones.
    pub fn hit_test_closest(&self, point: Point, payload: &T, max_distance: f64) -> Option<ZoneId> {
        if let Some(hit) = self
            .zones
            .peek()
            .iter()
            .rev()
            .find(|z| {
                z.accepts_payload(payload)
                    && (*z.rect.peek()).map(|r| r.contains(point)).unwrap_or(false)
            })
            .map(|z| z.id)
        {
            return Some(hit);
        }
        let mut best: Option<(ZoneId, f64)> = None;
        for z in self.acceptable(payload) {
            let Some(r) = *z.rect.peek() else { continue };
            let c = r.center();
            let (dx, dy) = (c.x - point.x, c.y - point.y);
            let d = (dx * dx + dy * dy).sqrt();
            if d <= max_distance && best.map(|(_, bd)| d < bd).unwrap_or(true) {
                best = Some((z.id, d));
            }
        }
        best.map(|(id, _)| id)
    }

    /// Re-measure every mounted zone's client rect and **wait** for the
    /// measurements to land - unlike [`Self::refresh_rects`], which fires
    /// and forgets. Use before a hit-test that must see fresh geometry
    /// (e.g. retrying a missed touch drop after a layout change).
    pub async fn measure_all(&self) {
        let zones: Vec<_> = self
            .zones
            .peek()
            .iter()
            .map(|z| (z.mounted.peek().clone(), z.rect))
            .collect();
        for (mounted, mut rect) in zones {
            if let Some(m) = mounted {
                if let Ok(r) = m.get_client_rect().await {
                    rect.set(Some(Rect::new(
                        r.origin.x,
                        r.origin.y,
                        r.size.width,
                        r.size.height,
                    )));
                }
            }
        }
    }

    /// Re-measure every mounted zone's client rect (async, spawned).
    pub fn refresh_rects(&self) {
        for zone in self.zones.peek().iter() {
            let mounted = zone.mounted.peek().clone();
            let mut rect = zone.rect;
            if let Some(m) = mounted {
                spawn(async move {
                    if let Ok(r) = m.get_client_rect().await {
                        rect.set(Some(Rect::new(
                            r.origin.x,
                            r.origin.y,
                            r.size.width,
                            r.size.height,
                        )));
                    }
                });
            }
        }
    }
}

/// A payload-type-erased "re-measure your zones" channel, shared by every
/// registry under one provider tree.
///
/// Cached client rects go stale the moment layout moves under a live drag -
/// scrolling being the everyday case. Registries are per payload type, but
/// the things that move layout (an auto-scrolling container, your own
/// scroll surface, a collapsing panel) shouldn't need to know any payload
/// type to say "geometry changed". Each provider registers a thunk here
/// that re-measures its own registry **only while it has a drag in
/// flight**, so pinging the channel from every scroll event costs nothing
/// while idle.
///
/// [`crate::autoscroll::AutoScroll`] pings this automatically after every
/// scroll it performs (and on any other scroll of its container); grab the
/// channel with [`crate::core::hooks::use_rect_refresh`] to wire up custom
/// layout mutators.
pub struct RectRefresh {
    thunks: Signal<Vec<(u64, Callback<()>)>>,
}

impl Copy for RectRefresh {}
impl Clone for RectRefresh {
    fn clone(&self) -> Self {
        *self
    }
}
impl PartialEq for RectRefresh {
    fn eq(&self, other: &Self) -> bool {
        self.thunks == other.thunks
    }
}

impl RectRefresh {
    /// Wrap an existing signal. Prefer [`crate::core::hooks::use_dnd_provider`],
    /// which creates one per provider *tree* (nested providers inherit and
    /// re-provide the outermost channel).
    pub fn from_signal(thunks: Signal<Vec<(u64, Callback<()>)>>) -> Self {
        Self { thunks }
    }

    /// Ask every provider in the tree to re-measure its zones. Providers
    /// without a drag in flight ignore the ping, so this is safe to call
    /// from high-frequency sources like scroll events.
    pub fn refresh_all(&self) {
        for (_, thunk) in self.thunks.peek().iter() {
            thunk.call(());
        }
    }

    /// Number of registered providers. Diagnostics and tests.
    pub fn len(&self) -> usize {
        self.thunks.peek().len()
    }

    /// Whether any provider is registered.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Add (or replace, by key) a provider's re-measure thunk.
    pub(crate) fn register(&mut self, key: u64, thunk: Callback<()>) {
        let mut thunks = self.thunks.write();
        if let Some(existing) = thunks.iter_mut().find(|(k, _)| *k == key) {
            existing.1 = thunk;
        } else {
            thunks.push((key, thunk));
        }
    }

    /// Remove a provider's thunk (call when the provider unmounts).
    pub(crate) fn unregister(&mut self, key: u64) {
        self.thunks.write().retain(|(k, _)| *k != key);
    }
}

/// Sort zones spatially: measured rects by (top, reading order), unmeasured
/// last in their original relative order. Reading order within a row is
/// left-to-right in LTR and right-to-left in RTL, so keyboard traversal
/// follows what the user sees either way.
fn spatial_sort<T: Clone + 'static>(zones: &mut [ZoneRecord<T>], dir: Direction) {
    let reading_x = move |x: f64| match dir {
        Direction::Ltr => x,
        Direction::Rtl => -x,
    };
    zones.sort_by(|a, b| match (*a.rect.peek(), *b.rect.peek()) {
        (Some(ra), Some(rb)) => (ra.y, reading_x(ra.x))
            .partial_cmp(&(rb.y, reading_x(rb.x)))
            .unwrap_or(std::cmp::Ordering::Equal),
        (Some(_), None) => std::cmp::Ordering::Less,
        (None, Some(_)) => std::cmp::Ordering::Greater,
        (None, None) => std::cmp::Ordering::Equal,
    });
}

/// Cyclic index stepping: `None` current starts at the first (or last)
/// element depending on direction. Pure, for testability.
pub(crate) fn cycle(len: usize, current: Option<usize>, step: isize) -> Option<usize> {
    if len == 0 {
        return None;
    }
    Some(match current {
        None => {
            if step >= 0 {
                0
            } else {
                len - 1
            }
        }
        Some(ix) => (ix as isize + step).rem_euclid(len as isize) as usize,
    })
}

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

    #[test]
    fn cycle_steps_and_wraps() {
        assert_eq!(cycle(0, None, 1), None);
        assert_eq!(cycle(3, None, 1), Some(0));
        assert_eq!(cycle(3, None, -1), Some(2));
        assert_eq!(cycle(3, Some(2), 1), Some(0));
        assert_eq!(cycle(3, Some(0), -1), Some(2));
        assert_eq!(cycle(3, Some(1), 1), Some(2));
    }
}