lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `FileUpload`: a file input styled as a drop zone.

// cspell:words ondragenter ondragleave

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::icons::{icon_svg, lucide};

/// The text under the prompt: the file name, or the count template for several files.
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()),
    }
}

/// Props for [`FileUpload`].
#[derive(Props, Clone, PartialEq)]
pub struct FileUploadProps {
    /// Id of the file input; generated when unset.
    #[props(into)]
    pub id: Option<String>,
    /// Prompt shown when there are no children.
    #[props(default = "Choose a file or drag it here".to_string(), into)]
    pub label: String,
    /// Secondary text under the prompt, such as accepted types and size limits.
    #[props(into)]
    pub hint: Option<String>,
    /// Text for several selected files; `{count}` is replaced with the number of files.
    #[props(default = "{count} files selected".to_string(), into)]
    pub selected_files_label: String,
    /// Extra classes for the file input.
    #[props(into)]
    pub input_class: Option<String>,
    /// Called with the names of the selected or dropped files.
    pub on_files_change: Option<EventHandler<Vec<String>>>,
    /// Fires when the file input changes; read the files with `event.files()`.
    pub onchange: Option<EventHandler<FormEvent>>,
    /// Fires when files are dropped on the zone; read them with `event.data_transfer().files()`.
    pub ondrop: Option<EventHandler<DragEvent>>,
    /// Extra classes appended after the Lumen class on the drop zone.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute, such as `accept`, `multiple`, `name`, or
    /// `disabled`. Like lumen-react they land on the file input.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
    /// Replaces the `label` prompt.
    pub children: Element,
}

/// A drop zone around a native file input. Clicking opens the file dialog; dragging files over
/// the zone sets `data-state="drag-over"`; the selected file names are announced politely.
#[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);
    // A drop on the web also changes the input; skip announcing the same files twice.
    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"
        );
    }
}