RendyUI English

组件 / 文件上传

文件上传

文本输入 · React / TypeScript Free

录制演示

文件上传 实现预览

源码

file-upload.tsx
"use client";

/**
 * File upload — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 *
 * A dropzone with file rows underneath: each row shows its type, size and a
 * live progress bar with a soft light sweep, then a check, or the reason it
 * failed with a retry. Removing a row aborts a running upload.
 */
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import {
  CheckCheck,
  File,
  FileImage,
  FileSpreadsheet,
  FileText,
  RotateCcw,
  Upload,
  X,
  type LucideIcon,
} from "lucide-react";
import { cn, useControllable } from "../internal";

export type UploadItemStatus = "uploading" | "done" | "error";

export type UploadItem = {
  id: string;
  name: string;
  size: number;
  status: UploadItemStatus;
  progress?: number;
  error?: string;
  kind?: string;
};

export interface FileUploadProps {
  items?: UploadItem[];
  defaultItems?: UploadItem[];
  onItemsChange?: (items: UploadItem[]) => void;
  upload?: (
    file: File,
    onProgress: (progress: number) => void,
    signal: AbortSignal,
  ) => Promise<void>;
  onFilesAdded?: (files: File[]) => void;
  accept?: string;
  multiple?: boolean;
  maxSize?: number;
  maxFiles?: number;
  title?: React.ReactNode;
  hint?: React.ReactNode;
  name?: string;
  disabled?: boolean;
  className?: string;
}

function formatBytes(bytes: number) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
  const mb = bytes / (1024 * 1024);
  return `${mb >= 10 ? Math.round(mb) : mb.toFixed(1)} MB`;
}

function extensionOf(name: string, kind?: string) {
  if (kind) return kind.toLowerCase();
  const parts = name.split(".");
  return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
}

const IMAGE_EXT = ["jpg", "jpeg", "png", "gif", "webp", "svg", "heic", "avif"];
const SHEET_EXT = ["csv", "tsv", "xls", "xlsx"];

function kindInfo(item: UploadItem): { Icon: LucideIcon; className: string } {
  const ext = extensionOf(item.name, item.kind);
  if (ext === "pdf") return { Icon: FileText, className: "bg-[var(--danger-soft)] text-danger" };
  if (IMAGE_EXT.includes(ext)) return { Icon: FileImage, className: "bg-[var(--select-soft)] text-select" };
  if (SHEET_EXT.includes(ext)) return { Icon: FileSpreadsheet, className: "bg-[var(--success-soft)] text-success" };
  return { Icon: File, className: "bg-muted text-fg-subtle" };
}

/**
 * File upload: a dropzone button (drag or click), then one row per file with
 * type glyph, size, live progress bar, and retry / cancel / remove actions.
 */
export function FileUpload({
  items: itemsProp,
  defaultItems,
  onItemsChange,
  upload,
  onFilesAdded,
  accept,
  multiple,
  maxSize,
  maxFiles,
  title,
  hint,
  name,
  disabled,
  className,
}: FileUploadProps) {
  const reduce = useReducedMotion();
  const [items, setItems] = useControllable<UploadItem[]>(
    itemsProp,
    defaultItems ?? [],
    onItemsChange,
  );
  const [dragOver, setDragOver] = React.useState(false);
  const [live, setLive] = React.useState("");
  const inputRef = React.useRef<HTMLInputElement>(null);
  const dropzoneRef = React.useRef<HTMLButtonElement>(null);
  const rowButtons = React.useRef(new Map<string, HTMLButtonElement>());
  const files = React.useRef(new Map<string, File>());
  const aborts = React.useRef(new Map<string, AbortController>());
  const counter = React.useRef(0);
  const itemsRef = React.useRef(items);
  itemsRef.current = items;
  const nextId = () => `upload-${++counter.current}`;

  const update = (id: string, patch: Partial<UploadItem>) => {
    setItems((prev) => prev.map((item) => (item.id === id ? { ...item, ...patch } : item)));
  };

  const startUpload = (id: string, file: File) => {
    if (!upload) {
      update(id, { status: "done", progress: 100 });
      return;
    }
    const controller = new AbortController();
    aborts.current.set(id, controller);
    update(id, { status: "uploading", progress: 0, error: undefined });
    upload(
      file,
      (progress) => update(id, { progress: Math.max(0, Math.min(100, Math.round(progress))) }),
      controller.signal,
    )
      .then(() => {
        aborts.current.delete(id);
        update(id, { status: "done", progress: 100 });
        setLive(`${file.name} uploaded`);
      })
      .catch((error: unknown) => {
        aborts.current.delete(id);
        const cancelled = controller.signal.aborted;
        update(id, {
          status: "error",
          error: cancelled
            ? "Upload cancelled"
            : error instanceof Error && error.message
              ? error.message
              : "Upload failed",
        });
        if (!cancelled) setLive(`${file.name} failed to upload`);
      });
  };

  const matchesAccept = (file: File) => {
    if (!accept) return true;
    const tokens = accept
      .split(",")
      .map((token) => token.trim().toLowerCase())
      .filter(Boolean);
    if (!tokens.length) return true;
    const lowerName = file.name.toLowerCase();
    const type = (file.type || "").toLowerCase();
    return tokens.some((token) => {
      if (token.startsWith(".")) return lowerName.endsWith(token);
      if (token.endsWith("/*")) return type.startsWith(token.slice(0, -1));
      return type === token;
    });
  };

  const addFiles = (incoming: FileList | File[]) => {
    if (disabled) return;
    const list = Array.from(incoming);
    if (!list.length) return;

    const accepted: File[] = [];
    const rejected: UploadItem[] = [];
    const reject = (file: File, reason: string) => {
      rejected.push({
        id: nextId(),
        name: file.name,
        size: file.size,
        status: "error",
        error: reason,
        kind: extensionOf(file.name),
      });
    };

    for (const file of list) {
      if (!matchesAccept(file)) reject(file, "Unsupported type");
      else if (maxSize !== undefined && file.size > maxSize)
        reject(file, `Over ${formatBytes(maxSize)} · ${formatBytes(file.size)}`);
      else accepted.push(file);
    }

    const limit = maxFiles ?? accepted.length;
    const remaining = Math.max(0, limit - itemsRef.current.length - rejected.length);
    const overflowed = accepted.slice(remaining);
    for (const file of overflowed) reject(file, "File limit reached");
    const uploadable = accepted.slice(0, remaining);

    const addedItems: UploadItem[] = [
      ...uploadable.map((file) => ({
        id: nextId(),
        name: file.name,
        size: file.size,
        status: "uploading" as const,
        progress: upload ? 0 : 100,
        kind: extensionOf(file.name),
      })),
      ...rejected,
    ];
    setItems((prev) => [...prev, ...addedItems]);

    const lines: string[] = [];
    if (uploadable.length) lines.push(`${uploadable.length} file${uploadable.length === 1 ? "" : "s"} added`);
    for (const item of rejected) lines.push(`${item.name} rejected: ${item.error}`);
    setLive(lines.join(". "));

    onFilesAdded?.(uploadable);
    uploadable.forEach((file, index) => {
      const item = addedItems[index];
      files.current.set(item.id, file);
      startUpload(item.id, file);
    });
  };

  const removeItem = (id: string) => {
    const current = itemsRef.current;
    const index = current.findIndex((item) => item.id === id);
    const target = current[index];
    if (!target) return;
    aborts.current.get(id)?.abort();
    aborts.current.delete(id);
    files.current.delete(id);
    setItems((prev) => prev.filter((item) => item.id !== id));
    setLive(`${target.name} removed`);
    const neighbor = current[index + 1] ?? current[index - 1];
    window.requestAnimationFrame(() => {
      const button = neighbor ? rowButtons.current.get(neighbor.id) : undefined;
      if (button) button.focus();
      else dropzoneRef.current?.focus();
    });
  };

  const retryItem = (id: string) => {
    const item = itemsRef.current.find((entry) => entry.id === id);
    const file = files.current.get(id);
    if (file && item) {
      setLive(`Retrying ${item.name}`);
      startUpload(id, file);
    } else {
      update(id, { status: "done", progress: 100, error: undefined });
    }
  };

  const cancelItem = (id: string) => {
    aborts.current.get(id)?.abort();
  };

  const hintId = React.useId();

  return (
    <div className={cn("flex flex-col gap-2", disabled && "opacity-60", className)}>
      <button
        type="button"
        ref={dropzoneRef}
        disabled={disabled}
        aria-describedby={hint ? hintId : undefined}
        onClick={() => inputRef.current?.click()}
        onDragOver={(event) => {
          event.preventDefault();
          if (!disabled) setDragOver(true);
        }}
        onDragLeave={() => setDragOver(false)}
        onDrop={(event) => {
          event.preventDefault();
          setDragOver(false);
          addFiles(event.dataTransfer.files);
        }}
        className={cn(
          "flex w-full flex-col items-center gap-2 rounded-[12px] bg-subtle px-6 py-8 text-center outline-none",
          "transition-colors focus-visible:ring-2 focus-visible:ring-select/60",
          dragOver && !disabled && "ring-2 ring-select/40",
          disabled && "cursor-not-allowed",
        )}
      >
        <span className="grid size-10 place-items-center rounded-full bg-surface text-fg-muted shadow-[var(--shadow-btn-secondary)]">
          <Upload className="size-4" aria-hidden />
        </span>
        <span className="text-[13px] font-medium text-fg">
          {title ?? (
            <>
              Drop files here or <span className="text-select">browse</span>
            </>
          )}
        </span>
        {hint ? (
          <span id={hintId} className="text-[12px] text-fg-subtle">
            {hint}
          </span>
        ) : null}
      </button>
      <input
        ref={inputRef}
        type="file"
        name={name}
        accept={accept}
        multiple={multiple}
        className="hidden"
        onChange={(event) => {
          if (event.target.files) addFiles(event.target.files);
          event.target.value = "";
        }}
      />

      <div className="flex flex-col gap-2">
        <AnimatePresence initial={false}>
          {items.map((item) => {
            const { Icon, className: kindClass } = kindInfo(item);
            const progress = item.progress ?? 0;
            const failed = item.status === "error";
            const uploading = item.status === "uploading";
            return (
              <motion.div
                key={item.id}
                layout={!reduce}
                initial={reduce ? false : { opacity: 0, y: -4 }}
                animate={{ opacity: 1, y: 0 }}
                exit={reduce ? undefined : { opacity: 0, scale: 0.98 }}
                transition={{ duration: 0.15, ease: [0.2, 0, 0, 1] }}
                className={cn(
                  "flex items-center gap-3 rounded-[10px] border border-border bg-surface px-3 py-2.5",
                  failed && "border-danger/40",
                )}
              >
                <span className={cn("grid size-9 shrink-0 place-items-center rounded-[8px]", kindClass)}>
                  <Icon className="size-4" aria-hidden />
                </span>
                <div className="min-w-0 flex-1">
                  <div className="truncate text-[13px] font-medium text-fg">{item.name}</div>
                  {failed ? (
                    <div className="text-[12px] text-danger">{item.error ?? "Upload failed"}</div>
                  ) : uploading ? (
                    <div className="mt-1.5 flex items-center gap-2">
                      <span className="shrink-0 text-[12px] tabular-nums text-fg-subtle">
                        {formatBytes(item.size)} · {progress}%
                      </span>
                      <div
                        role="progressbar"
                        aria-valuemin={0}
                        aria-valuemax={100}
                        aria-valuenow={progress}
                        aria-label={`Uploading ${item.name}`}
                        className="h-1 flex-1 overflow-hidden rounded-full bg-track"
                      >
                        <div
                          className="relative h-full overflow-hidden rounded-full bg-select transition-[width] duration-150"
                          style={{ width: `${Math.max(2, progress)}%` }}
                        >
                          {!reduce ? (
                            <motion.span
                              aria-hidden
                              className="absolute inset-y-0 w-1/2 bg-gradient-to-r from-transparent via-white/50 to-transparent"
                              animate={{ x: ["-120%", "220%"] }}
                              transition={{ duration: 1.1, repeat: Infinity, ease: "linear" }}
                            />
                          ) : null}
                        </div>
                      </div>
                    </div>
                  ) : (
                    <div className="text-[12px] text-fg-subtle">
                      {formatBytes(item.size)} · Uploaded
                    </div>
                  )}
                </div>
                {item.status === "done" ? (
                  <CheckCheck className="size-4 shrink-0 text-success" aria-hidden />
                ) : null}
                {failed ? (
                  <button
                    type="button"
                    aria-label={`Retry ${item.name}`}
                    disabled={disabled}
                    onClick={() => retryItem(item.id)}
                    className="grid size-7 shrink-0 place-items-center rounded-full text-fg-subtle transition-colors outline-none hover:bg-subtle hover:text-fg focus-visible:ring-2 focus-visible:ring-select/60"
                  >
                    <RotateCcw className="size-3.5" aria-hidden />
                  </button>
                ) : null}
                {uploading ? (
                  <button
                    type="button"
                    ref={(node) => {
                      if (node) rowButtons.current.set(item.id, node);
                      else rowButtons.current.delete(item.id);
                    }}
                    aria-label={`Cancel ${item.name}`}
                    disabled={disabled}
                    onClick={() => cancelItem(item.id)}
                    className="grid size-7 shrink-0 place-items-center rounded-full text-fg-subtle transition-colors outline-none hover:bg-subtle hover:text-fg focus-visible:ring-2 focus-visible:ring-select/60"
                  >
                    <X className="size-3.5" aria-hidden />
                  </button>
                ) : (
                  <button
                    type="button"
                    ref={(node) => {
                      if (node) rowButtons.current.set(item.id, node);
                      else rowButtons.current.delete(item.id);
                    }}
                    aria-label={`Remove ${item.name}`}
                    disabled={disabled}
                    onClick={() => removeItem(item.id)}
                    className="grid size-7 shrink-0 place-items-center rounded-full text-fg-subtle transition-colors outline-none hover:bg-subtle hover:text-fg focus-visible:ring-2 focus-visible:ring-select/60"
                  >
                    <X className="size-3.5" aria-hidden />
                  </button>
                )}
              </motion.div>
            );
          })}
        </AnimatePresence>
      </div>

      <div role="status" aria-live="polite" className="sr-only">
        {live}
      </div>
    </div>
  );
}

export default FileUpload;

使用说明

把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。

包依赖 · lucide-react、motion、react

共享源码 · internal.ts

参数

名称类型说明
`items / defaultItems / onItemsChange``UploadItem[] / … / (items) => void`Rows: { id, name, size, status: "uploading"
`upload``(file, onProgress, signal) => Promise<void>`Runs per accepted file; report 0–100, resolve to finish, reject to fail. Removing a row aborts it. Without it files list as done.
`onFilesAdded``(files: File[]) => void`The accepted files as they arrive.
`accept / multiple / maxSize / maxFiles``string / boolean / number / number`Wrong types and files over maxSize (bytes) are listed as failed.
`title / hint``ReactNode`Dropzone copy, e.g. “PDF, JPG, PNG or CSV up to 10 MB”.
`name / disabled``string / boolean`Name for the hidden file input.