Skip to main content

lumen_dioxus/pickers/
file_upload.rs

1//! `FileUpload`: a file input styled as a drop zone.
2
3// cspell:words ondragenter ondragleave
4
5use dioxus::prelude::*;
6
7use crate::class::compose;
8use crate::hooks::use_unique_id;
9use crate::icons::{icon_svg, lucide};
10
11/// The text under the prompt: the file name, or the count template for several files.
12pub(crate) fn selected_files_text(names: &[String], template: &str) -> String {
13    match names {
14        [] => String::new(),
15        [single] => single.clone(),
16        many => template.replace("{count}", &many.len().to_string()),
17    }
18}
19
20/// Props for [`FileUpload`].
21#[derive(Props, Clone, PartialEq)]
22pub struct FileUploadProps {
23    /// Id of the file input; generated when unset.
24    #[props(into)]
25    pub id: Option<String>,
26    /// Prompt shown when there are no children.
27    #[props(default = "Choose a file or drag it here".to_string(), into)]
28    pub label: String,
29    /// Secondary text under the prompt, such as accepted types and size limits.
30    #[props(into)]
31    pub hint: Option<String>,
32    /// Text for several selected files; `{count}` is replaced with the number of files.
33    #[props(default = "{count} files selected".to_string(), into)]
34    pub selected_files_label: String,
35    /// Extra classes for the file input.
36    #[props(into)]
37    pub input_class: Option<String>,
38    /// Called with the names of the selected or dropped files.
39    pub on_files_change: Option<EventHandler<Vec<String>>>,
40    /// Fires when the file input changes; read the files with `event.files()`.
41    pub onchange: Option<EventHandler<FormEvent>>,
42    /// Fires when files are dropped on the zone; read them with `event.data_transfer().files()`.
43    pub ondrop: Option<EventHandler<DragEvent>>,
44    /// Extra classes appended after the Lumen class on the drop zone.
45    #[props(into)]
46    pub class: Option<String>,
47    /// Any other `<input>` or global attribute, such as `accept`, `multiple`, `name`, or
48    /// `disabled`. Like lumen-react they land on the file input.
49    #[props(extends = GlobalAttributes, extends = input)]
50    pub attributes: Vec<Attribute>,
51    /// Replaces the `label` prompt.
52    pub children: Element,
53}
54
55/// A drop zone around a native file input. Clicking opens the file dialog; dragging files over
56/// the zone sets `data-state="drag-over"`; the selected file names are announced politely.
57#[component]
58pub fn FileUpload(props: FileUploadProps) -> Element {
59    let generated = use_unique_id();
60    let input_id = props
61        .id
62        .clone()
63        .unwrap_or_else(|| format!("ui-file-upload-{generated}"));
64    let mut names = use_signal(Vec::<String>::new);
65    let mut dragging = use_signal(|| false);
66    // A drop on the web also changes the input; skip announcing the same files twice.
67    let mut dropped = use_signal(|| None::<Vec<String>>);
68    let text = selected_files_text(&names.read(), &props.selected_files_label);
69    let state = if dragging() {
70        "drag-over"
71    } else if names.read().is_empty() {
72        "idle"
73    } else {
74        "selected"
75    };
76    let class = compose([Some("ui-file-upload"), props.class.as_deref()]);
77    let input_class = compose([Some("ui-file-upload__input"), props.input_class.as_deref()]);
78    let (on_files_change, onchange, ondrop) = (props.on_files_change, props.onchange, props.ondrop);
79    let has_children = !matches!(props.children, Ok(ref node) if *node == VNode::placeholder());
80
81    rsx! {
82        label {
83            class,
84            "data-state": state,
85            "data-ui-file-upload": "true",
86            r#for: input_id.clone(),
87            ondragenter: move |_| dragging.set(true),
88            ondragover: move |_| {
89                if !dragging() {
90                    dragging.set(true);
91                }
92            },
93            ondragleave: move |_| dragging.set(false),
94            ondrop: move |event: DragEvent| {
95                dragging.set(false);
96                let files: Vec<String> = event
97                    .data_transfer()
98                    .files()
99                    .iter()
100                    .map(dioxus::html::FileData::name)
101                    .collect();
102
103                if !files.is_empty() {
104                    names.set(files.clone());
105                    dropped.set(Some(files.clone()));
106
107                    if let Some(handler) = on_files_change {
108                        handler.call(files);
109                    }
110                }
111
112                if let Some(handler) = ondrop {
113                    handler.call(event);
114                }
115            },
116            input {
117                class: input_class,
118                "data-ui-file-upload-input": "true",
119                id: input_id,
120                r#type: "file",
121                onchange: move |event: FormEvent| {
122                    let files: Vec<String> = event
123                        .files()
124                        .iter()
125                        .map(dioxus::html::FileData::name)
126                        .collect();
127                    let duplicate = dropped.take().as_ref() == Some(&files);
128                    names.set(files.clone());
129
130                    if !duplicate && let Some(handler) = on_files_change {
131                        handler.call(files);
132                    }
133
134                    if let Some(handler) = onchange {
135                        handler.call(event);
136                    }
137                },
138                ..props.attributes,
139            }
140            {icon_svg(&lucide::UPLOAD, "ui-icon__svg lucide-upload ui-file-upload__icon")}
141            span { class: "ui-file-upload__prompt",
142                if has_children {
143                    {props.children}
144                } else {
145                    "{props.label}"
146                }
147            }
148            if let Some(hint) = props.hint {
149                span { class: "ui-file-upload__hint", "{hint}" }
150            }
151            span {
152                aria_live: "polite",
153                class: "ui-file-upload__files",
154                "data-ui-file-upload-files": "true",
155                "{text}"
156            }
157        }
158    }
159}
160
161#[cfg(test)]
162mod tests {
163    use super::selected_files_text;
164
165    #[test]
166    fn file_text_names_one_file_and_counts_several() {
167        let template = "{count} files selected";
168        assert_eq!(selected_files_text(&[], template), "");
169        assert_eq!(
170            selected_files_text(&["a.pdf".to_string()], template),
171            "a.pdf"
172        );
173        assert_eq!(
174            selected_files_text(&["a".to_string(), "b".to_string()], "{count} of {count}"),
175            "2 of 2"
176        );
177    }
178}