use dioxus::prelude::*;
use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::icons::{icon_svg, lucide};
pub(crate) fn selected_files_text(names: &[String], template: &str) -> String {
match names {
[] => String::new(),
[single] => single.clone(),
many => template.replace("{count}", &many.len().to_string()),
}
}
#[derive(Props, Clone, PartialEq)]
pub struct FileUploadProps {
#[props(into)]
pub id: Option<String>,
#[props(default = "Choose a file or drag it here".to_string(), into)]
pub label: String,
#[props(into)]
pub hint: Option<String>,
#[props(default = "{count} files selected".to_string(), into)]
pub selected_files_label: String,
#[props(into)]
pub input_class: Option<String>,
pub on_files_change: Option<EventHandler<Vec<String>>>,
pub onchange: Option<EventHandler<FormEvent>>,
pub ondrop: Option<EventHandler<DragEvent>>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = input)]
pub attributes: Vec<Attribute>,
pub children: Element,
}
#[component]
pub fn FileUpload(props: FileUploadProps) -> Element {
let generated = use_unique_id();
let input_id = props
.id
.clone()
.unwrap_or_else(|| format!("ui-file-upload-{generated}"));
let mut names = use_signal(Vec::<String>::new);
let mut dragging = use_signal(|| false);
let mut dropped = use_signal(|| None::<Vec<String>>);
let text = selected_files_text(&names.read(), &props.selected_files_label);
let state = if dragging() {
"drag-over"
} else if names.read().is_empty() {
"idle"
} else {
"selected"
};
let class = compose([Some("ui-file-upload"), props.class.as_deref()]);
let input_class = compose([Some("ui-file-upload__input"), props.input_class.as_deref()]);
let (on_files_change, onchange, ondrop) = (props.on_files_change, props.onchange, props.ondrop);
let has_children = !matches!(props.children, Ok(ref node) if *node == VNode::placeholder());
rsx! {
label {
class,
"data-state": state,
"data-ui-file-upload": "true",
r#for: input_id.clone(),
ondragenter: move |_| dragging.set(true),
ondragover: move |_| {
if !dragging() {
dragging.set(true);
}
},
ondragleave: move |_| dragging.set(false),
ondrop: move |event: DragEvent| {
dragging.set(false);
let files: Vec<String> = event
.data_transfer()
.files()
.iter()
.map(dioxus::html::FileData::name)
.collect();
if !files.is_empty() {
names.set(files.clone());
dropped.set(Some(files.clone()));
if let Some(handler) = on_files_change {
handler.call(files);
}
}
if let Some(handler) = ondrop {
handler.call(event);
}
},
input {
class: input_class,
"data-ui-file-upload-input": "true",
id: input_id,
r#type: "file",
onchange: move |event: FormEvent| {
let files: Vec<String> = event
.files()
.iter()
.map(dioxus::html::FileData::name)
.collect();
let duplicate = dropped.take().as_ref() == Some(&files);
names.set(files.clone());
if !duplicate && let Some(handler) = on_files_change {
handler.call(files);
}
if let Some(handler) = onchange {
handler.call(event);
}
},
..props.attributes,
}
{icon_svg(&lucide::UPLOAD, "ui-icon__svg lucide-upload ui-file-upload__icon")}
span { class: "ui-file-upload__prompt",
if has_children {
{props.children}
} else {
"{props.label}"
}
}
if let Some(hint) = props.hint {
span { class: "ui-file-upload__hint", "{hint}" }
}
span {
aria_live: "polite",
class: "ui-file-upload__files",
"data-ui-file-upload-files": "true",
"{text}"
}
}
}
}
#[cfg(test)]
mod tests {
use super::selected_files_text;
#[test]
fn file_text_names_one_file_and_counts_several() {
let template = "{count} files selected";
assert_eq!(selected_files_text(&[], template), "");
assert_eq!(
selected_files_text(&["a.pdf".to_string()], template),
"a.pdf"
);
assert_eq!(
selected_files_text(&["a".to_string(), "b".to_string()], "{count} of {count}"),
"2 of 2"
);
}
}