跳至正文
获取 Pro
业务区块B.09

文件上传区

FreeRegistry
components/linyi/file-upload.tsx
lucide-reactmotion
"use client";
 
import * as React from "react";
import { motion, AnimatePresence } from "motion/react";
import { Upload, FileText, CheckCircle2, AlertCircle, X, Plus } from "lucide-react";
import { cn } from "@/lib/cn";
import { SPRING_SNAPPY, SPRING_PROGRESS } from "@/lib/motion";
 
export interface UploadQueueItem {
id: string;
name: string;
size: number;
progress: number;
status: "uploading" | "done" | "error";
errorMessage?: string;
}
 
export interface FileUploadProps {
files?: UploadQueueItem[];
defaultFiles?: UploadQueueItem[];
accept?: string;
maxFiles?: number;
maxSizeBytes?: number;
onFilesChange?: (files: UploadQueueItem[]) => void;
onFilesAdded?: (files: File[]) => void;
onRemoveFile?: (id: string) => void;
onReject?: (reason: string, file: File) => void;
onUpload?: (file: File, onProgress: (pct: number) => void) => Promise<void>;
showSampleButton?: boolean;
compact?: boolean;
className?: string;
}
 
const DEFAULT_QUEUE: UploadQueueItem[] = [
{
id: "init-1",
name: "linyi-theme.css",
size: 28_400,
progress: 100,
status: "done",
},
];
 
const SAMPLE_FILES = [
{ name: "linyi-tokens.json", size: 42_800 },
{ name: "design-spec-v2.pdf", size: 1_480_000 },
{ name: "hero-preview.png", size: 628_400 },
];
 
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
}
 
export function FileUpload({
files: controlledFiles,
defaultFiles = DEFAULT_QUEUE,
accept,
maxFiles = 5,
maxSizeBytes,
onFilesChange,
onFilesAdded,
onRemoveFile,
onReject,
onUpload,
showSampleButton = true,
compact = false,
className,
}: FileUploadProps) {
const [internalQueue, setInternalQueue] = React.useState<UploadQueueItem[]>(defaultFiles);
const [isDragging, setIsDragging] = React.useState(false);
 
const queue = controlledFiles ?? internalQueue;
const inputRef = React.useRef<HTMLInputElement | null>(null);
const dragDepthRef = React.useRef(0);
const sampleIdxRef = React.useRef(0);
const timersRef = React.useRef<Map<string, ReturnType<typeof setInterval>>>(new Map());
 
const updateQueue = React.useCallback(
(updater: (prev: UploadQueueItem[]) => UploadQueueItem[]) => {
if (controlledFiles !== undefined) {
onFilesChange?.(updater(controlledFiles));
return;
}
setInternalQueue((prev) => {
const next = updater(prev);
onFilesChange?.(next);
return next;
});
},
[controlledFiles, onFilesChange]
);
 
React.useEffect(() => {
const timers = timersRef.current;
return () => {
timers.forEach((intervalId) => clearInterval(intervalId));
timers.clear();
};
}, []);
 
const startSimulatedUpload = (itemId: string) => {
const existing = timersRef.current.get(itemId);
if (existing) clearInterval(existing);
 
const intervalId = setInterval(() => {
updateQueue((prev) =>
prev.map((item) => {
if (item.id !== itemId) return item;
const next = Math.min(100, item.progress + 18);
if (next >= 100) {
const timer = timersRef.current.get(itemId);
if (timer) {
clearInterval(timer);
timersRef.current.delete(itemId);
}
return { ...item, progress: 100, status: "done" };
}
return { ...item, progress: next };
})
);
}, 180);
 
timersRef.current.set(itemId, intervalId);
};
 
const enqueueEntries = (entries: Array<{ name: string; size: number; file?: File }>) => {
if (entries.length === 0) return;
 
const acceptedEntries: Array<{ name: string; size: number; file?: File }> = [];
for (const entry of entries) {
if (maxSizeBytes && entry.size > maxSizeBytes && entry.file) {
onReject?.(`文件体积超过限制(最大 ${formatBytes(maxSizeBytes)})`, entry.file);
continue;
}
acceptedEntries.push(entry);
}
 
if (acceptedEntries.length === 0) return;
 
const realFiles = acceptedEntries
.map((entry) => entry.file)
.filter((f): f is File => Boolean(f));
if (realFiles.length > 0) {
onFilesAdded?.(realFiles);
}
 
const newItems: Array<{ item: UploadQueueItem; file?: File }> = acceptedEntries.map(
(entry, index) => ({
item: {
id: `f-${Date.now()}-${index}-${Math.random().toString(36).slice(2, 6)}`,
name: entry.name,
size: entry.size,
progress: onUpload && entry.file ? 0 : 14,
status: "uploading",
},
file: entry.file,
})
);
 
updateQueue((prev) => [...newItems.map((n) => n.item), ...prev].slice(0, maxFiles));
 
newItems.forEach(({ item, file }) => {
if (onUpload && file) {
onUpload(file, (pct) => {
const clamped = Math.max(0, Math.min(100, Math.round(pct)));
updateQueue((prev) =>
prev.map((q) =>
q.id === item.id
? { ...q, progress: clamped, status: clamped >= 100 ? "done" : "uploading" }
: q
)
);
})
.then(() => {
updateQueue((prev) =>
prev.map((q) => (q.id === item.id ? { ...q, progress: 100, status: "done" } : q))
);
})
.catch((err) => {
const msg = err instanceof Error ? err.message : "上传失败";
updateQueue((prev) =>
prev.map((q) =>
q.id === item.id ? { ...q, status: "error", errorMessage: msg } : q
)
);
});
} else {
startSimulatedUpload(item.id);
}
});
};
 
const handleFileInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files ? Array.from(e.target.files) : [];
enqueueEntries(files.map((f) => ({ name: f.name, size: f.size, file: f })));
e.target.value = "";
};
 
const handleDragEnter = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
dragDepthRef.current += 1;
setIsDragging(true);
};
 
const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
};
 
const handleDragLeave = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
if (dragDepthRef.current === 0) {
setIsDragging(false);
}
};
 
const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
e.preventDefault();
dragDepthRef.current = 0;
setIsDragging(false);
const files = e.dataTransfer.files ? Array.from(e.dataTransfer.files) : [];
enqueueEntries(files.map((f) => ({ name: f.name, size: f.size, file: f })));
};
 
const addSampleFile = () => {
const sample = SAMPLE_FILES[sampleIdxRef.current % SAMPLE_FILES.length];
sampleIdxRef.current += 1;
enqueueEntries([sample]);
};
 
const removeItem = (id: string) => {
const timer = timersRef.current.get(id);
if (timer) {
clearInterval(timer);
timersRef.current.delete(id);
}
onRemoveFile?.(id);
updateQueue((prev) => prev.filter((item) => item.id !== id));
};
 
const latestItem = queue[0];
 
if (compact) {
return (
<div
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={cn(
"w-full max-w-[248px] rounded-well border border-dashed p-3.5 transition-colors",
isDragging ? "border-accent bg-accent-soft" : "border-line-strong bg-surface"
)}
>
<input
ref={inputRef}
type="file"
multiple
accept={accept}
onChange={handleFileInputChange}
className="hidden"
aria-hidden="true"
/>
 
<div className="flex flex-col items-center gap-2 text-center">
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-accent-soft text-accent">
<Upload className="h-3.5 w-3.5" aria-hidden="true" />
</span>
<div className="text-[11px] font-medium text-fg">
{isDragging ? "松开以添加文件" : "拖拽或点击上传文件"}
</div>
<div className="flex items-center gap-1.5">
<button
type="button"
onClick={() => inputRef.current?.click()}
className="cursor-pointer rounded-pill border border-line bg-surface-2 px-2.5 py-1 text-[10px] font-medium text-fg transition-colors hover:bg-well"
>
选择文件
</button>
{showSampleButton && (
<button
type="button"
onClick={addSampleFile}
className="cursor-pointer rounded-pill bg-accent-soft px-2.5 py-1 text-[10px] font-medium text-accent transition-opacity hover:opacity-85"
>
模拟上传
</button>
)}
</div>
</div>
 
{latestItem && (
<div className="mt-3 space-y-1 border-t border-line pt-2.5">
<div className="flex items-center justify-between gap-2 text-[10px]">
<span className="truncate text-fg-secondary">{latestItem.name}</span>
<span className="font-mono-num text-fg-muted">{latestItem.progress}%</span>
</div>
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={latestItem.progress}
aria-label={`${latestItem.name} 上传进度`}
className="h-1 w-full overflow-hidden rounded-full bg-well"
>
<motion.div
initial={false}
animate={{ scaleX: latestItem.progress / 100 }}
transition={SPRING_PROGRESS}
className={cn(
"h-full w-full origin-left rounded-full",
latestItem.status === "error"
? "bg-danger"
: latestItem.status === "done"
? "bg-success"
: "bg-accent"
)}
/>
</div>
</div>
)}
</div>
);
}
 
return (
<div className={cn("w-full max-w-lg space-y-3.5", className)}>
<input
ref={inputRef}
type="file"
multiple
accept={accept}
onChange={handleFileInputChange}
className="hidden"
aria-hidden="true"
/>
 
{/* Dropzone */}
<div
onDragEnter={handleDragEnter}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
className={cn(
"flex flex-col items-center justify-center gap-3 rounded-panel border border-dashed px-6 py-7 text-center transition-colors",
isDragging
? "border-accent bg-accent-soft"
: "border-line-strong bg-surface hover:border-fg-muted"
)}
>
<span
className={cn(
"flex h-11 w-11 items-center justify-center rounded-full border transition-colors",
isDragging
? "border-accent-border bg-accent text-accent-fg"
: "border-line bg-surface-2 text-accent"
)}
>
<Upload className="h-5 w-5" aria-hidden="true" />
</span>
 
<div>
<div className="text-xs font-semibold text-fg">
{isDragging ? "松开鼠标即可加入上传队列" : "将文件拖拽至此处,或从本地选择"}
</div>
<p className="mt-1 text-[11px] text-fg-muted">
支持多文件批量上传,队列最多保留 {maxFiles} 条记录
{maxSizeBytes ? `,单文件不超过 ${formatBytes(maxSizeBytes)}` : ""}
</p>
</div>
 
<div className="flex flex-wrap items-center justify-center gap-2 pt-1">
<button
type="button"
onClick={() => inputRef.current?.click()}
className="ui-btn ui-btn-solid h-control-sm px-4 text-xs"
>
<span>选择本地文件</span>
</button>
{showSampleButton && (
<button
type="button"
onClick={addSampleFile}
className="inline-flex h-control-sm cursor-pointer items-center gap-1 rounded-pill border border-line-strong bg-surface-2 px-3.5 text-xs font-medium text-fg transition-colors hover:bg-well"
>
<Plus className="h-3.5 w-3.5 text-accent" aria-hidden="true" />
<span>添加示例文件</span>
</button>
)}
</div>
</div>
 
{/* Upload Queue */}
<div className="space-y-2">
<div className="flex items-center justify-between px-1 text-[11px] text-fg-muted">
<span>传输队列</span>
<span className="font-mono-num">
{queue.filter((q) => q.status === "done").length} / {queue.length} 已完成
</span>
</div>
 
<AnimatePresence mode="popLayout" initial={false}>
{queue.length === 0 ? (
<motion.div
key="queue-empty"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="rounded-well border border-line bg-surface-2 py-6 text-center text-xs text-fg-muted"
>
当前队列为空,可点击上方按钮添加文件
</motion.div>
) : (
queue.map((item) => {
const done = item.status === "done";
const failed = item.status === "error";
return (
<motion.div
key={item.id}
layout
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, x: 16 }}
transition={SPRING_SNAPPY}
className="rounded-well border border-line bg-surface p-3 shadow-panel"
>
<div className="flex items-center justify-between gap-2.5">
<div className="flex min-w-0 items-center gap-2.5">
<span
className={cn(
"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-control border",
failed
? "border-danger-border bg-danger-soft text-danger"
: done
? "border-success-border bg-success-soft text-success"
: "border-line bg-surface-2 text-fg-secondary"
)}
>
{failed ? (
<AlertCircle className="h-4 w-4" aria-hidden="true" />
) : done ? (
<CheckCircle2 className="h-4 w-4" aria-hidden="true" />
) : (
<FileText className="h-4 w-4" aria-hidden="true" />
)}
</span>
<div className="min-w-0">
<div className="truncate text-xs font-medium text-fg">{item.name}</div>
<div className="mt-0.5 flex items-center gap-2 font-mono-num text-[10px] text-fg-muted">
<span>{formatBytes(item.size)}</span>
<span>·</span>
<span
className={
failed ? "text-danger" : done ? "text-success" : "text-accent"
}
>
{failed
? item.errorMessage ?? "上传失败"
: done
? "已完成"
: `上传中 ${item.progress}%`}
</span>
</div>
</div>
</div>
 
<button
type="button"
onClick={() => removeItem(item.id)}
aria-label={`移除文件:${item.name}`}
className="flex h-6 w-6 flex-shrink-0 cursor-pointer items-center justify-center rounded-pill text-fg-muted transition-colors hover:bg-well hover:text-fg"
>
<X className="h-3.5 w-3.5" aria-hidden="true" />
</button>
</div>
 
<div
role="progressbar"
aria-valuemin={0}
aria-valuemax={100}
aria-valuenow={item.progress}
aria-label={`${item.name} 上传进度`}
className="mt-2.5 h-1.5 w-full overflow-hidden rounded-full bg-well"
>
<motion.div
initial={false}
animate={{ scaleX: item.progress / 100 }}
transition={SPRING_PROGRESS}
className={cn(
"h-full w-full origin-left rounded-full",
failed ? "bg-danger" : done ? "bg-success" : "bg-accent"
)}
/>
</div>
</motion.div>
);
})
)}
</AnimatePresence>
</div>
</div>
);
}