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

use dioxus::html::{FileData, HasFileData};
use dioxus::prelude::*;

use crate::core::{client_point, element_point, Point};

/// A batch of dropped or selected files plus its interaction coordinates.
#[derive(Clone, PartialEq)]
pub struct FileDrop {
    pub files: Vec<FileData>,
    /// Pointer position in client (viewport) coordinates.
    ///
    /// File-picker selections have no drop position, so this is `(0, 0)`.
    pub client: Point,
    /// Pointer position relative to the drop zone element.
    ///
    /// File-picker selections have no drop position, so this is `(0, 0)`.
    pub element: Point,
}

/// Why a file was rejected by a [`FileFilter`].
///
/// Non-exhaustive: new acceptance rules mean new rejection reasons, so
/// keep a wildcard arm with a generic "not accepted" message.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum FileRejection {
    /// Extension not in the allow-list.
    Extension,
    /// MIME type not in the allow-list.
    ContentType,
    /// Larger than `max_size` bytes.
    TooLarge,
    /// Batch exceeded `max_files`; this file was over the limit.
    TooMany,
}

/// Declarative acceptance rules for dropped or picker-selected files.
///
/// **Advisory, not a security boundary.** These rules match on the browser-
/// and OS-reported name, content type and size, all of which are
/// attacker-controllable: a `.exe` can be renamed `photo.png` and report
/// `content_type: "image/png"`, and `size` is self-reported. Use the filter
/// for UX (rejecting obviously wrong drops early), but validate the actual
/// bytes server-side or via content sniffing before trusting a file.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FileFilter {
    extensions: Vec<String>,
    content_types: Vec<String>,
    max_size: Option<u64>,
    max_files: Option<usize>,
}

impl FileFilter {
    pub fn new() -> Self {
        Self::default()
    }

    /// Allow only these extensions (case-insensitive, leading dot optional).
    pub fn extensions<I, S>(mut self, exts: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.extensions = exts
            .into_iter()
            .map(|s| normalize_extension(&s.into()))
            .filter(|s| !s.is_empty())
            .collect();
        self
    }

    /// Allow only these MIME types.
    ///
    /// Supported patterns:
    ///
    /// - exact types: `"application/pdf"`
    /// - top-level wildcards: `"image/*"`
    /// - all typed files: `"*/*"`
    /// - structured suffix wildcards: `"application/*+json"` and `"*/*+json"`
    pub fn content_types<I, S>(mut self, types: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.content_types = types
            .into_iter()
            .map(|s| normalize_content_type(&s.into()))
            .filter(|s| !s.is_empty())
            .collect();
        self
    }

    /// Reject files larger than this many bytes.
    pub fn max_size(mut self, bytes: u64) -> Self {
        self.max_size = Some(bytes);
        self
    }

    /// Accept at most this many files per incoming batch.
    pub fn max_files(mut self, n: usize) -> Self {
        self.max_files = Some(n);
        self
    }

    /// Check a single file against the rules (ignores `max_files`).
    pub fn check(&self, file: &FileData) -> Result<(), FileRejection> {
        if !self.extensions.is_empty() {
            // ASCII-lowercase to match `normalize_extension`; a full Unicode
            // `to_lowercase()` here could case-fold a non-ASCII filename
            // differently from the (ASCII-lowered) extension and spuriously
            // mismatch. File extensions are ASCII in practice.
            let name = file.name().to_ascii_lowercase();
            let ok = self
                .extensions
                .iter()
                .any(|ext| name.ends_with(&format!(".{ext}")));
            if !ok {
                return Err(FileRejection::Extension);
            }
        }
        if !self.content_types.is_empty() {
            let ct = file
                .content_type()
                .map(|s| normalize_content_type(&s))
                .unwrap_or_default();
            let ok = self
                .content_types
                .iter()
                .any(|allowed| content_type_matches(allowed, &ct));
            if !ok {
                return Err(FileRejection::ContentType);
            }
        }
        if let Some(max) = self.max_size {
            if file.size() > max {
                return Err(FileRejection::TooLarge);
            }
        }
        Ok(())
    }

    /// Split a batch into `(accepted, rejected)` applying every rule.
    pub fn partition(
        &self,
        files: Vec<FileData>,
    ) -> (Vec<FileData>, Vec<(FileData, FileRejection)>) {
        let mut ok = Vec::new();
        let mut bad = Vec::new();
        for file in files {
            if let Some(max) = self.max_files {
                if ok.len() >= max {
                    bad.push((file, FileRejection::TooMany));
                    continue;
                }
            }
            match self.check(&file) {
                Ok(()) => ok.push(file),
                Err(why) => bad.push((file, why)),
            }
        }
        (ok, bad)
    }

    /// Build the advisory `accept` value for the native file picker.
    ///
    /// The picker grammar cannot express every rule supported by
    /// `FileFilter` (sizes, counts, or structured-suffix wildcards), so the
    /// selected files still pass through `partition` before callbacks fire.
    fn picker_accept(&self) -> Option<String> {
        let mut hints = self
            .extensions
            .iter()
            .map(|extension| format!(".{extension}"))
            .collect::<Vec<_>>();

        for content_type in &self.content_types {
            let Some((ty, subtype)) = split_content_type(content_type) else {
                continue;
            };
            // HTML file inputs understand exact MIME types and top-level
            // wildcards. Broader and structured-suffix wildcards remain
            // enforced after selection without accidentally hiding valid
            // files in the dialog.
            if ty == "*" || ty.contains('*') || (subtype != "*" && subtype.contains('*')) {
                continue;
            }
            if !hints.contains(content_type) {
                hints.push(content_type.clone());
            }
        }

        (!hints.is_empty()).then(|| hints.join(","))
    }
}

fn normalize_extension(ext: &str) -> String {
    ext.trim().trim_start_matches('.').to_ascii_lowercase()
}

fn normalize_content_type(content_type: &str) -> String {
    content_type
        .split_once(';')
        .map(|(base, _)| base)
        .unwrap_or(content_type)
        .trim()
        .to_ascii_lowercase()
}

fn split_content_type(content_type: &str) -> Option<(&str, &str)> {
    let (ty, subtype) = content_type.split_once('/')?;
    if ty.is_empty() || subtype.is_empty() || subtype.contains('/') {
        return None;
    }
    Some((ty, subtype))
}

fn content_type_matches(pattern: &str, content_type: &str) -> bool {
    let Some((pattern_type, pattern_subtype)) = split_content_type(pattern) else {
        return false;
    };
    let Some((actual_type, actual_subtype)) = split_content_type(content_type) else {
        return false;
    };

    if pattern_type == "*" && pattern_subtype == "*" {
        return true;
    }
    if pattern_type == "*" && !pattern_subtype.starts_with("*+") {
        return false;
    }
    if pattern_type != "*" && pattern_type != actual_type {
        return false;
    }
    if pattern_subtype == "*" {
        return true;
    }
    if let Some(suffix) = pattern_subtype.strip_prefix("*+") {
        return actual_subtype
            .rsplit_once('+')
            .map(|(_, actual_suffix)| actual_suffix == suffix)
            .unwrap_or(false);
    }

    pattern_subtype == actual_subtype
}

fn deliver_files(
    files: Vec<FileData>,
    filter: Option<&FileFilter>,
    on_files: &EventHandler<FileDrop>,
    on_rejected: Option<&EventHandler<Vec<(FileData, FileRejection)>>>,
    client: Point,
    element: Point,
) {
    if files.is_empty() {
        return;
    }
    let (accepted, rejected) = match filter {
        Some(filter) => filter.partition(files),
        None => (files, Vec::new()),
    };
    if !rejected.is_empty() {
        if let Some(handler) = on_rejected {
            handler.call(rejected);
        }
    }
    if !accepted.is_empty() {
        on_files.call(FileDrop {
            files: accepted,
            client,
            element,
        });
    }
}

/// A zone that accepts files dragged in from the operating system or chosen
/// from the native file picker opened by clicking the zone.
///
/// Independent of `DndContext` - native files don't come from inside your
/// app, so no provider is required.
///
/// While a drag hovers the zone the div carries `data-over="true"` (absent
/// otherwise), so the classic "highlight the dropzone" style needs no
/// `on_hover` wiring: Tailwind `data-over:border-blue-500`, CSS
/// `[data-over]`.
#[component]
pub fn FileDropZone(
    /// Acceptance rules; everything is accepted when omitted.
    #[props(default)]
    filter: Option<FileFilter>,
    /// Fired with accepted dropped or selected files (if at least one passed).
    on_files: EventHandler<FileDrop>,
    /// Fired with rejected dropped or selected files, if any.
    #[props(default)]
    on_rejected: Option<EventHandler<Vec<(FileData, FileRejection)>>>,
    /// Fired with `true` when a drag hovers the zone, `false` when it leaves.
    #[props(default)]
    on_hover: Option<EventHandler<bool>>,
    /// Allow selecting more than one file in the native picker.
    #[props(default = true)]
    multiple: bool,
    /// Disable picker activation and native file input.
    #[props(default)]
    disabled: bool,
    /// Accessible name for the keyboard-focusable drop zone.
    #[props(default = "Choose or drop files".to_string())]
    label: String,
    #[props(extends = div, extends = GlobalAttributes)] attributes: Vec<Attribute>,
    children: Element,
) -> Element {
    let mut depth = use_signal(|| 0u32);
    let input_id = use_hook(|| {
        format!(
            "dioxus-dnd-file-input-{}",
            dioxus::core::current_scope_id().0
        )
    });
    let picker_input_id = input_id.clone();
    let picker_accept = filter.as_ref().and_then(FileFilter::picker_accept);
    let picker_filter = filter.clone();
    let picker_on_files = on_files;
    let picker_on_rejected = on_rejected;
    let open_picker = use_callback(move |_: ()| {
        if disabled {
            return;
        }
        // Clear the value before opening so choosing the same file twice
        // still produces a change event.
        let script = format!(
            "const input = document.getElementById({picker_input_id:?}); \
             if (input) {{ input.value = ''; input.click(); }}"
        );
        let _ = dioxus::document::eval(&script);
    });
    let mut attributes = attributes;
    crate::core::components::protect_attributes(
        &mut attributes,
        &[
            "data-over",
            "data-disabled",
            "role",
            "tabindex",
            "aria-label",
            "aria-disabled",
            "onclick",
            "onkeydown",
            "ondragover",
            "ondragenter",
            "ondragleave",
            "ondrop",
        ],
    );

    rsx! {
        div {
            "data-over": if !disabled && depth() > 0 { "true" },
            "data-disabled": if disabled { "true" },
            role: "button",
            tabindex: if disabled { -1_i64 } else { 0 },
            aria_label: label,
            aria_disabled: disabled,
            onclick: move |_| open_picker.call(()),
            onkeydown: move |event: KeyboardEvent| {
                if disabled {
                    return;
                }
                let key = event.key();
                if matches!(key, Key::Enter)
                    || matches!(&key, Key::Character(value) if value == " ")
                {
                    event.prevent_default();
                    open_picker.call(());
                }
            },
            ondragover: move |evt: DragEvent| {
                // Required: without preventDefault the browser never delivers
                // the drop (it would open the file instead).
                evt.prevent_default();
            },
            ondragenter: move |evt: DragEvent| {
                evt.prevent_default();
                if disabled {
                    return;
                }
                let d = depth() + 1;
                depth.set(d);
                if d == 1 {
                    if let Some(h) = &on_hover {
                        h.call(true);
                    }
                }
            },
            ondragleave: move |_| {
                if disabled {
                    depth.set(0);
                    return;
                }
                let d = depth().saturating_sub(1);
                depth.set(d);
                if d == 0 {
                    if let Some(h) = &on_hover {
                        h.call(false);
                    }
                }
            },
            ondrop: move |evt: DragEvent| {
                evt.prevent_default();
                depth.set(0);
                if let Some(h) = &on_hover {
                    h.call(false);
                }
                if disabled {
                    return;
                }
                deliver_files(
                    evt.files(),
                    filter.as_ref(),
                    &on_files,
                    on_rejected.as_ref(),
                    client_point(&evt),
                    element_point(&evt),
                );
            },
            ..attributes,
            {children}
            input {
                id: input_id,
                type: "file",
                accept: picker_accept,
                multiple,
                disabled,
                hidden: true,
                // The programmatic input click bubbles. Stop it here so it
                // cannot reopen the picker through the zone's click handler.
                onclick: move |evt: MouseEvent| evt.stop_propagation(),
                onchange: move |evt: FormEvent| {
                    if disabled {
                        return;
                    }
                    deliver_files(
                        evt.files(),
                        picker_filter.as_ref(),
                        &picker_on_files,
                        picker_on_rejected.as_ref(),
                        Point::default(),
                        Point::default(),
                    );
                },
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use dioxus::html::NativeFileData;
    use std::path::PathBuf;
    use std::pin::Pin;

    /// Minimal test double for the platform file object.
    struct MockFile {
        name: &'static str,
        size: u64,
        content_type: Option<&'static str>,
    }

    impl NativeFileData for MockFile {
        fn name(&self) -> String {
            self.name.to_string()
        }
        fn size(&self) -> u64 {
            self.size
        }
        fn last_modified(&self) -> u64 {
            0
        }
        fn path(&self) -> PathBuf {
            PathBuf::new()
        }
        fn content_type(&self) -> Option<String> {
            self.content_type.map(str::to_string)
        }
        fn read_bytes(
            &self,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<bytes::Bytes, dioxus::CapturedError>>>>
        {
            Box::pin(std::future::ready(Ok(bytes::Bytes::new())))
        }
        fn byte_stream(
            &self,
        ) -> Pin<
            Box<
                dyn futures_util::Stream<Item = Result<bytes::Bytes, dioxus::CapturedError>>
                    + Send
                    + 'static,
            >,
        > {
            Box::pin(futures_util::stream::empty())
        }
        fn read_string(
            &self,
        ) -> Pin<Box<dyn std::future::Future<Output = Result<String, dioxus::CapturedError>>>>
        {
            Box::pin(std::future::ready(Ok(String::new())))
        }
        fn inner(&self) -> &dyn std::any::Any {
            self
        }
    }

    fn file(name: &'static str, size: u64, ct: Option<&'static str>) -> FileData {
        FileData::new(MockFile {
            name,
            size,
            content_type: ct,
        })
    }

    #[test]
    fn extension_filter_is_case_insensitive() {
        let f = FileFilter::new().extensions(["png", ".JPG", " gif "]);
        assert!(f.check(&file("Photo.PNG", 10, None)).is_ok());
        assert!(f.check(&file("photo.jpg", 10, None)).is_ok());
        assert!(f.check(&file("clip.GIF", 10, None)).is_ok());
        assert_eq!(
            f.check(&file("notes.txt", 10, None)),
            Err(FileRejection::Extension)
        );
        // extension must match at the end, not merely appear
        assert_eq!(
            f.check(&file("png.txt", 10, None)),
            Err(FileRejection::Extension)
        );
    }

    #[test]
    fn content_type_wildcards() {
        let f = FileFilter::new().content_types(["image/*", "application/pdf"]);
        assert!(f.check(&file("a", 1, Some("image/webp"))).is_ok());
        assert!(f.check(&file("b", 1, Some("application/pdf"))).is_ok());
        assert_eq!(
            f.check(&file("c", 1, Some("text/plain"))),
            Err(FileRejection::ContentType)
        );
        // missing content type fails a type-restricted filter
        assert_eq!(
            f.check(&file("d", 1, None)),
            Err(FileRejection::ContentType)
        );
    }

    #[test]
    fn content_type_wildcards_match_whole_type_only() {
        let f = FileFilter::new().content_types(["image/*"]);
        assert!(f.check(&file("a", 1, Some("image/svg+xml"))).is_ok());
        assert_eq!(
            f.check(&file("b", 1, Some("imageevil/png"))),
            Err(FileRejection::ContentType)
        );
        assert_eq!(
            f.check(&file("c", 1, Some("application/image"))),
            Err(FileRejection::ContentType)
        );
        assert_eq!(
            f.check(&file("d", 1, Some("image/png/extra"))),
            Err(FileRejection::ContentType)
        );
    }

    #[test]
    fn content_type_matching_normalizes_case_whitespace_and_parameters() {
        let f = FileFilter::new().content_types([" Application/PDF ", "text/plain"]);
        assert!(f.check(&file("a", 1, Some("application/pdf"))).is_ok());
        assert!(f
            .check(&file("b", 1, Some("TEXT/PLAIN; charset=utf-8")))
            .is_ok());
    }

    #[test]
    fn content_type_all_wildcard_accepts_any_typed_file() {
        let f = FileFilter::new().content_types(["*/*"]);
        assert!(f.check(&file("a", 1, Some("image/png"))).is_ok());
        assert!(f
            .check(&file("b", 1, Some("application/octet-stream")))
            .is_ok());
        assert_eq!(
            f.check(&file("c", 1, None)),
            Err(FileRejection::ContentType)
        );
    }

    #[test]
    fn content_type_structured_suffix_wildcards() {
        let app_json = FileFilter::new().content_types(["application/*+json"]);
        assert!(app_json
            .check(&file("a", 1, Some("application/ld+json")))
            .is_ok());
        assert!(app_json
            .check(&file("b", 1, Some("application/vnd.api+json")))
            .is_ok());
        assert_eq!(
            app_json.check(&file("c", 1, Some("text/ld+json"))),
            Err(FileRejection::ContentType)
        );
        assert_eq!(
            app_json.check(&file("d", 1, Some("application/json"))),
            Err(FileRejection::ContentType)
        );

        let any_json = FileFilter::new().content_types(["*/*+json"]);
        assert!(any_json
            .check(&file("e", 1, Some("application/problem+json")))
            .is_ok());
        assert!(any_json
            .check(&file("f", 1, Some("model/gltf+json")))
            .is_ok());
        assert_eq!(
            any_json.check(&file("g", 1, Some("application/json"))),
            Err(FileRejection::ContentType)
        );
    }

    #[test]
    fn malformed_content_type_patterns_do_not_match() {
        let f = FileFilter::new().content_types(["image", "image/", "/png", "image/png/extra"]);
        assert_eq!(
            f.check(&file("a", 1, Some("image/png"))),
            Err(FileRejection::ContentType)
        );
    }

    #[test]
    fn unsupported_subtype_only_wildcard_does_not_match() {
        let f = FileFilter::new().content_types(["*/json"]);
        assert_eq!(
            f.check(&file("a", 1, Some("application/json"))),
            Err(FileRejection::ContentType)
        );
        assert_eq!(
            f.check(&file("b", 1, Some("text/json"))),
            Err(FileRejection::ContentType)
        );
    }

    #[test]
    fn size_limit() {
        let f = FileFilter::new().max_size(100);
        assert!(f.check(&file("ok", 100, None)).is_ok());
        assert_eq!(
            f.check(&file("big", 101, None)),
            Err(FileRejection::TooLarge)
        );
    }

    #[test]
    fn partition_applies_count_after_other_rules() {
        let f = FileFilter::new().extensions(["png"]).max_files(2);
        let batch = vec![
            file("a.png", 1, None),
            file("b.txt", 1, None), // rejected on extension, doesn't consume a slot
            file("c.png", 1, None),
            file("d.png", 1, None), // over the count
        ];
        let (ok, bad) = f.partition(batch);
        assert_eq!(
            ok.iter().map(|f| f.name()).collect::<Vec<_>>(),
            vec!["a.png", "c.png"]
        );
        assert_eq!(bad.len(), 2);
        assert_eq!(bad[0].1, FileRejection::Extension);
        assert_eq!(bad[1].1, FileRejection::TooMany);
    }

    #[test]
    fn picker_accept_uses_only_rules_the_dialog_can_represent() {
        let filter = FileFilter::new()
            .extensions(["png", ".JPG"])
            .content_types(["image/*", "application/pdf", "application/*+json", "*/*"]);

        assert_eq!(
            filter.picker_accept().as_deref(),
            Some(".png,.jpg,image/*,application/pdf")
        );
        assert_eq!(
            FileFilter::new().max_size(10).picker_accept(),
            None,
            "non-picker rules must not create an empty accept restriction"
        );
    }
}