dioxus-dnd 1.0.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
//! Small model helpers for applying completed drops to app-owned state.
//!
//! The crate never touches your data: drops arrive as [`DropOutcome`]s and
//! you decide what they mean. These helpers cover the most common meaning,
//! the remove-from-source, append-to-target dance, without imposing bounds
//! on your item type: no `Clone` (the payload arrives owned), no
//! `PartialEq` (matching is by the key you extract).

use std::collections::HashMap;

use super::{DropEffect, DropOutcome, ZoneId};

/// Apply a drop to a `HashMap<ZoneId, Vec<T>>` model.
///
/// `Move` removes the matching item from `outcome.from` before appending it
/// to `outcome.to`. `Copy` leaves the source alone and passes the payload
/// through `clone_item` first, which is where you should assign a fresh id.
///
/// Semantics worth knowing:
///
/// - Removal matches **every** item in the source whose key equals the
///   payload's key. Keys are expected to be unique within a zone; if they
///   are not, a single `Move` prunes all of them.
/// - A `Move` where `from == Some(to)` removes and re-appends, so dropping
///   an item back onto its own zone sends it to the **end of that list**.
/// - A `Move` with `from: None` (payload from outside any zone, e.g. a
///   palette) skips removal and just appends.
/// - An unknown `to` zone is created on the fly rather than dropping the
///   item on the floor.
pub fn apply_clone_or_move<T, K>(
    zones: &mut HashMap<ZoneId, Vec<T>>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    mut clone_item: impl FnMut(T) -> T,
) where
    K: PartialEq,
{
    let DropOutcome {
        payload,
        from,
        to,
        effect,
        ..
    } = outcome;
    let item = if effect == DropEffect::Copy {
        clone_item(payload)
    } else {
        if let Some(from) = from {
            let payload_key = key(&payload);
            if let Some(source) = zones.get_mut(&from) {
                source.retain(|item| key(item) != payload_key);
            }
        }
        payload
    };

    zones.entry(to).or_default().push(item);
}

/// Apply a drop between two plain `Vec<T>` lists.
///
/// `Move` removes the matching item from `source` before appending it to
/// `target`. `Copy` leaves the source alone and passes the payload through
/// `clone_item` first, which is where you should assign a fresh id.
///
/// You choose which lists to pass, so the outcome's `from` and `to` fields
/// are **ignored** here; only `payload` and `effect` are consulted. Pass
/// `None` for `source` when the payload came from outside any list. As with
/// [`apply_clone_or_move`], removal matches every item whose key equals the
/// payload's key.
pub fn apply_list_clone_or_move<T, K>(
    source: Option<&mut Vec<T>>,
    target: &mut Vec<T>,
    outcome: DropOutcome<T>,
    key: impl Fn(&T) -> K,
    mut clone_item: impl FnMut(T) -> T,
) where
    K: PartialEq,
{
    let DropOutcome {
        payload, effect, ..
    } = outcome;
    let item = if effect == DropEffect::Copy {
        clone_item(payload)
    } else {
        if let Some(source) = source {
            let payload_key = key(&payload);
            source.retain(|item| key(item) != payload_key);
        }
        payload
    };

    target.push(item);
}

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

    #[derive(Debug, Clone, PartialEq)]
    struct Card {
        id: u32,
        title: &'static str,
    }

    fn outcome(
        payload: Card,
        from: Option<ZoneId>,
        to: ZoneId,
        effect: DropEffect,
    ) -> DropOutcome<Card> {
        DropOutcome {
            payload,
            from,
            to,
            effect,
            client: Point::default(),
            element: Point::default(),
        }
    }

    #[test]
    fn move_removes_from_source_and_appends_to_target() {
        let a = ZoneId(1);
        let b = ZoneId(2);
        let mut zones = HashMap::from([
            (
                a,
                vec![
                    Card {
                        id: 1,
                        title: "one",
                    },
                    Card {
                        id: 2,
                        title: "two",
                    },
                ],
            ),
            (
                b,
                vec![Card {
                    id: 3,
                    title: "three",
                }],
            ),
        ]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 2,
                    title: "two",
                },
                Some(a),
                b,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            zones[&a],
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            zones[&b],
            vec![
                Card {
                    id: 3,
                    title: "three"
                },
                Card {
                    id: 2,
                    title: "two"
                }
            ]
        );
    }

    #[test]
    fn copy_leaves_source_and_allows_new_identity() {
        let a = ZoneId(1);
        let b = ZoneId(2);
        let mut zones = HashMap::from([
            (
                a,
                vec![Card {
                    id: 1,
                    title: "one",
                }],
            ),
            (b, Vec::new()),
        ]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(a),
                b,
                DropEffect::Copy,
            ),
            |card| card.id,
            |mut card| {
                card.id = 10;
                card
            },
        );

        assert_eq!(
            zones[&a],
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            zones[&b],
            vec![Card {
                id: 10,
                title: "one"
            }]
        );
    }

    /// Pins the self-drop semantics documented on `apply_clone_or_move`: a
    /// `Move` back onto the source zone reorders the item to the end.
    #[test]
    fn move_onto_own_zone_reorders_to_end() {
        let a = ZoneId(1);
        let mut zones = HashMap::from([(
            a,
            vec![
                Card {
                    id: 1,
                    title: "one",
                },
                Card {
                    id: 2,
                    title: "two",
                },
            ],
        )]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(a),
                a,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            zones[&a],
            vec![
                Card {
                    id: 2,
                    title: "two"
                },
                Card {
                    id: 1,
                    title: "one"
                }
            ]
        );
    }

    /// A payload from outside any zone (palette, external drop) has no
    /// source to prune; `Move` just appends.
    #[test]
    fn move_without_source_zone_just_appends() {
        let b = ZoneId(2);
        let mut zones = HashMap::from([(b, Vec::new())]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 7,
                    title: "seven",
                },
                None,
                b,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            zones[&b],
            vec![Card {
                id: 7,
                title: "seven"
            }]
        );
    }

    /// An unknown target zone is created rather than losing the item.
    #[test]
    fn unknown_target_zone_is_created() {
        let a = ZoneId(1);
        let ghost = ZoneId(99);
        let mut zones = HashMap::from([(
            a,
            vec![Card {
                id: 1,
                title: "one",
            }],
        )]);

        apply_clone_or_move(
            &mut zones,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(a),
                ghost,
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert!(zones[&a].is_empty());
        assert_eq!(
            zones[&ghost],
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
    }

    #[test]
    fn list_move_removes_from_source_and_appends_to_target() {
        let mut source = vec![
            Card {
                id: 1,
                title: "one",
            },
            Card {
                id: 2,
                title: "two",
            },
        ];
        let mut target = vec![Card {
            id: 3,
            title: "three",
        }];

        apply_list_clone_or_move(
            Some(&mut source),
            &mut target,
            outcome(
                Card {
                    id: 2,
                    title: "two",
                },
                Some(ZoneId(1)),
                ZoneId(2),
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            source,
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            target,
            vec![
                Card {
                    id: 3,
                    title: "three"
                },
                Card {
                    id: 2,
                    title: "two"
                }
            ]
        );
    }

    #[test]
    fn list_copy_leaves_source_and_allows_new_identity() {
        let mut source = vec![Card {
            id: 1,
            title: "one",
        }];
        let mut target = Vec::new();

        apply_list_clone_or_move(
            Some(&mut source),
            &mut target,
            outcome(
                Card {
                    id: 1,
                    title: "one",
                },
                Some(ZoneId(1)),
                ZoneId(2),
                DropEffect::Copy,
            ),
            |card| card.id,
            |mut card| {
                card.id = 10;
                card
            },
        );

        assert_eq!(
            source,
            vec![Card {
                id: 1,
                title: "one"
            }]
        );
        assert_eq!(
            target,
            vec![Card {
                id: 10,
                title: "one"
            }]
        );
    }

    /// `Move` into a list without a source (`None`) skips removal.
    #[test]
    fn list_move_without_source_just_appends() {
        let mut target = Vec::new();

        apply_list_clone_or_move(
            None,
            &mut target,
            outcome(
                Card {
                    id: 7,
                    title: "seven",
                },
                None,
                ZoneId(2),
                DropEffect::Move,
            ),
            |card| card.id,
            |card| card,
        );

        assert_eq!(
            target,
            vec![Card {
                id: 7,
                title: "seven"
            }]
        );
    }
}