| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611 |
- import React, { useState, useEffect } from 'react';
- import { useQuery } from '@tanstack/react-query';
- import { Button } from '@d8d/shared-ui-components/components/ui/button';
- import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@d8d/shared-ui-components/components/ui/dialog';
- import { Card, CardContent } from '@d8d/shared-ui-components/components/ui/card';
- import { toast } from 'sonner';
- import { fileClientManager, fileClient } from '../api/fileClient';
- import MinioUploader from './MinioUploader';
- import { Check, Upload, Eye, X, File as FileIcon, Image as ImageIcon } from 'lucide-react';
- import { cn } from '../utils/cn';
- import type { InferResponseType } from 'hono/client';
- type FileType = InferResponseType<typeof fileClient.index.$get, 200>['data'][0]
- export interface FileSelectorProps {
- value?: number | null | number[];
- onChange?: (fileId: number | null | number[]) => void;
- accept?: string;
- maxSize?: number;
- uploadPath?: string;
- previewSize?: 'small' | 'medium' | 'large';
- showPreview?: boolean;
- placeholder?: string;
- title?: string;
- description?: string;
- filterType?: 'image' | 'all' | string;
- allowMultiple?: boolean;
- /**
- * 仅上传模式 - 只显示上传区域,不显示现有文件列表
- * @default false
- *
- * 当设置为 true 时:
- * - 对话框只显示上传区域(MinioUploader)
- * - 不显示现有文件列表
- * - 不调用文件列表查询 API(性能优化)
- * - 上传成功后自动选中该文件并关闭对话框,直接返回 fileId
- *
- * 适用场景:需要快速上传文件而不需要从现有文件中选择时,
- * 如残疾人上传资料时避免加载大量缩略图导致的性能问题
- */
- uploadOnly?: boolean;
- }
- export const FileSelector: React.FC<FileSelectorProps> = ({
- value,
- onChange,
- accept = '*/*',
- maxSize = 10,
- uploadPath = '/files',
- previewSize = 'medium',
- showPreview = true,
- placeholder = '选择文件',
- title = '选择文件',
- description = '上传新文件或从已有文件中选择',
- filterType = 'all',
- allowMultiple = false,
- uploadOnly = false,
- }) => {
- const [isOpen, setIsOpen] = useState(false);
- const [selectedFile, setSelectedFile] = useState<FileType | null>(null);
- const [localSelectedFiles, setLocalSelectedFiles] = useState<number[]>([]);
- // 获取当前选中的文件详情 - 支持单值和数组
- const { data: currentFiles } = useQuery<FileType[]>({
- queryKey: ['file-details', value, allowMultiple],
- queryFn: async (): Promise<FileType[]> => {
- if (!value) return [];
- // 处理多选模式下的数组值
- if (allowMultiple && Array.isArray(value)) {
- if (value.length === 0) return [];
- // 批量获取多个文件详情
- const filePromises = value.map(async (fileId) => {
- try {
- const response = await fileClientManager.get()[':id']['$get']({ param: { id: Number(fileId) } });
- if (response.status === 200) {
- return response.json();
- }
- return null;
- } catch {
- return null;
- }
- });
- const files = await Promise.all(filePromises);
- return files.filter(file => file !== null);
- }
- // 处理单选模式下的单值
- if (!Array.isArray(value)) {
- const response = await fileClientManager.get()[':id']['$get']({ param: { id: Number(value) } });
- if (response.status !== 200) throw new Error('获取文件详情失败');
- return [await response.json()];
- }
- return [];
- },
- enabled: !!value,
- });
- // 当对话框打开时,设置当前选中的文件
- useEffect(() => {
- if (isOpen) {
- if (allowMultiple) {
- // 在多选模式下,使用 value 数组初始化本地选择
- const initialSelection = Array.isArray(value) ? value : [];
- setLocalSelectedFiles(initialSelection);
- } else if (value && currentFiles && currentFiles.length > 0) {
- setSelectedFile(currentFiles[0]);
- }
- }
- }, [isOpen, value, currentFiles, allowMultiple]);
- // 获取文件列表 - uploadOnly 模式下禁用查询以提高性能
- const { data: filesData, isLoading, refetch } = useQuery({
- queryKey: ['files-for-selection', filterType] as const,
- queryFn: async () => {
- const response = await fileClientManager.get().index.$get({
- query: {
- page: 1,
- pageSize: 50,
- ...(filterType !== 'all' && { keyword: filterType })
- }
- });
- if (response.status !== 200) throw new Error('获取文件列表失败');
- return response.json();
- },
- enabled: isOpen && !uploadOnly, // uploadOnly 模式下不执行查询
- });
- const files = filesData?.data?.filter((f) => {
- if (filterType === 'all') return true;
- if (filterType === 'image') return f?.type?.startsWith('image/');
- return f?.type?.includes(filterType);
- }) || [];
- const handleSelectFile = (file: FileType) => {
- if (allowMultiple) {
- setLocalSelectedFiles(prev => {
- const newSelection = prev.includes(file.id)
- ? prev.filter(id => id !== file.id)
- : [...prev, file.id];
- return newSelection;
- });
- } else {
- setSelectedFile(prevSelected => {
- if (prevSelected?.id === file.id) {
- return null;
- }
- return file;
- });
- }
- };
- const handleConfirm = () => {
- if (allowMultiple) {
- if (onChange) {
- onChange(localSelectedFiles);
- }
- setIsOpen(false);
- return;
- }
- if (!selectedFile) {
- toast.warning('请选择一个文件');
- return;
- }
- if (onChange) {
- onChange(selectedFile.id);
- }
- setIsOpen(false);
- setSelectedFile(null);
- };
- const handleCancel = () => {
- setIsOpen(false);
- setSelectedFile(null);
- // 取消时重置为初始的 value 值
- const initialSelection = allowMultiple && Array.isArray(value) ? value : [];
- setLocalSelectedFiles(initialSelection);
- };
- const handleUploadSuccess = async (_fileKey: string, _fileUrl: string, file: File) => {
- if (uploadOnly) {
- // uploadOnly 模式:上传成功后自动获取 fileId 并返回
- try {
- // 记录上传开始时间
- const uploadStartTime = Date.now();
- // 获取刚上传的文件的 ID(通过文件名、大小和时间戳匹配)
- const response = await fileClientManager.get().index.$get({
- query: {
- page: 1,
- pageSize: 50, // 获取更多结果以提高匹配概率
- }
- });
- if (response.status === 200) {
- const data = await response.json();
- // 多重匹配策略,提高准确性:
- // 1. 首先通过文件名和大小匹配
- // 2. 验证上传时间在最近 30 秒内
- // 3. 如果有多个匹配,选择最新的
- const matchCandidates = data.data?.filter((f: FileType) => {
- // 基础匹配:文件名和大小
- if (f.name !== file.name || f.size !== file.size) {
- return false;
- }
- // 时间验证:上传时间在最近 30 秒内(避免匹配旧文件)
- const fileUploadTime = new Date(f.uploadTime || '').getTime();
- const timeDiff = uploadStartTime - fileUploadTime;
- return timeDiff >= 0 && timeDiff < 30000; // 30 秒内
- }) || [];
- if (matchCandidates.length > 0) {
- // 选择最新的文件(按 uploadTime 降序排序)
- const uploadedFile = matchCandidates.sort((a: FileType, b: FileType) => {
- const timeA = new Date(a.uploadTime || '').getTime();
- const timeB = new Date(b.uploadTime || '').getTime();
- return timeB - timeA; // 降序
- })[0];
- // 直接返回 fileId 并关闭对话框
- if (allowMultiple) {
- onChange?.([uploadedFile.id]);
- } else {
- onChange?.(uploadedFile.id);
- }
- setIsOpen(false);
- toast.success('文件上传成功!');
- return;
- }
- }
- // 如果找不到文件,提示用户
- toast.error('无法获取上传的文件信息');
- } catch (error) {
- console.error('获取上传文件信息失败:', error);
- toast.error('获取上传文件信息失败');
- }
- } else {
- // 默认模式:提示用户从列表中选择
- toast.success('文件上传成功!请从列表中选择新上传的文件');
- refetch();
- }
- };
- const getPreviewSize = () => {
- switch (previewSize) {
- case 'small':
- return 'h-16 w-16';
- case 'medium':
- return 'h-24 w-24';
- case 'large':
- return 'h-32 w-32';
- default:
- return 'h-24 w-24';
- }
- };
- const getFileIcon = (fileType: string) => {
- if (fileType.startsWith('image/')) {
- return <ImageIcon className="h-8 w-8 text-gray-400" />;
- }
- if (fileType.startsWith('video/')) {
- return <FileIcon className="h-8 w-8 text-blue-500" />;
- }
- if (fileType.startsWith('audio/')) {
- return <FileIcon className="h-8 w-8 text-green-500" />;
- }
- if (fileType.includes('pdf')) {
- return <FileIcon className="h-8 w-8 text-red-500" />;
- }
- if (fileType.includes('text')) {
- return <FileIcon className="h-8 w-8 text-gray-600" />;
- }
- return <FileIcon className="h-8 w-8 text-gray-400" />;
- };
- const handleRemoveFile = (e: React.MouseEvent) => {
- e.stopPropagation();
- if (allowMultiple && Array.isArray(value)) {
- // 在多选模式下,移除所有选中文件
- onChange?.([]);
- } else {
- // 在单选模式下,设置为null
- onChange?.(null);
- }
- };
- const isSelected = (fileId: number) => {
- if (allowMultiple) {
- return localSelectedFiles.includes(fileId);
- }
- return selectedFile?.id === fileId;
- };
- return (
- <>
- <div className="space-y-4">
- {showPreview && (
- <div className="flex items-start space-x-4">
- {/* 预览区域 */}
- <div className="flex flex-wrap gap-2">
- {allowMultiple && Array.isArray(currentFiles) && currentFiles.length > 0 ? (
- // 多选模式下的预览
- currentFiles.map((file) => (
- <div key={file.id} className="relative group">
- <div
- className={cn(
- getPreviewSize(),
- "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
- )}
- onClick={() => setIsOpen(true)}
- >
- {file?.type ? (
- <div className="w-full h-full flex items-center justify-center">
- {file.type.startsWith('image/') ? (
- <img
- src={file.fullUrl}
- alt={file.name}
- className="w-full h-full object-cover"
- />
- ) : (
- <div className="flex flex-col items-center justify-center text-gray-400">
- {getFileIcon(file.type)}
- <span className="text-xs mt-1 text-center px-1 truncate max-w-full">
- {file.name}
- </span>
- </div>
- )}
- </div>
- ) : (
- <div className="flex flex-col items-center justify-center text-gray-400">
- <FileIcon className="h-8 w-8 mb-1" />
- <span className="text-xs">{placeholder}</span>
- </div>
- )}
- </div>
- <button
- type="button"
- className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
- onClick={(e) => {
- e.stopPropagation();
- if (allowMultiple && Array.isArray(value)) {
- const newValue = value.filter(id => id !== file.id);
- onChange?.(newValue);
- }
- }}
- >
- <X className="h-3 w-3" />
- </button>
- </div>
- ))
- ) : !allowMultiple && currentFiles && currentFiles.length > 0 ? (
- // 单选模式下的预览
- <div className="relative group">
- <div
- className={cn(
- getPreviewSize(),
- "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
- )}
- onClick={() => setIsOpen(true)}
- >
- {currentFiles[0]?.type ? (
- <div className="w-full h-full flex items-center justify-center">
- {currentFiles[0].type.startsWith('image/') ? (
- <img
- src={currentFiles[0].fullUrl}
- alt={currentFiles[0].name}
- className="w-full h-full object-cover"
- />
- ) : (
- <div className="flex flex-col items-center justify-center text-gray-400">
- {getFileIcon(currentFiles[0].type)}
- <span className="text-xs mt-1 text-center">{currentFiles[0].name}</span>
- </div>
- )}
- </div>
- ) : (
- <div className="flex flex-col items-center justify-center text-gray-400">
- <FileIcon className="h-8 w-8 mb-1" />
- <span className="text-xs">{placeholder}</span>
- </div>
- )}
- </div>
- {currentFiles[0] && (
- <button
- type="button"
- className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
- onClick={handleRemoveFile}
- >
- <X className="h-3 w-3" />
- </button>
- )}
- </div>
- ) : (
- // 没有选中文件时的占位符
- <div
- className={cn(
- getPreviewSize(),
- "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
- )}
- onClick={() => setIsOpen(true)}
- >
- <div className="flex flex-col items-center justify-center text-gray-400">
- <FileIcon className="h-8 w-8 mb-1" />
- <span className="text-xs">{placeholder}</span>
- </div>
- </div>
- )}
- </div>
- <div className="space-y-2">
- <Button
- type="button"
- variant="outline"
- onClick={() => setIsOpen(true)}
- className="text-sm"
- data-testid="file-selector-button"
- >
- {((allowMultiple && currentFiles && currentFiles.length > 0) ||
- (!allowMultiple && currentFiles && currentFiles.length > 0)) ? '更换文件' : placeholder}
- </Button>
- {!allowMultiple && currentFiles && currentFiles.length > 0 && (
- <p className="text-xs text-muted-foreground truncate w-40 sm:w-64">
- 当前: {currentFiles[0].name}
- </p>
- )}
- {allowMultiple && currentFiles && currentFiles.length > 0 && (
- <p className="text-xs text-muted-foreground">
- 已选择 {currentFiles.length} 个文件
- </p>
- )}
- </div>
- </div>
- )}
- {!showPreview && (
- <Button
- type="button"
- variant="outline"
- onClick={() => setIsOpen(true)}
- className="w-full"
- >
- {currentFiles ? '更换文件' : placeholder}
- </Button>
- )}
- </div>
- <Dialog open={isOpen} onOpenChange={setIsOpen}>
- <DialogContent className="max-w-4xl max-h-[90vh]" data-testid="file-selector-dialog">
- <DialogHeader>
- <DialogTitle>{title}</DialogTitle>
- <DialogDescription>
- {uploadOnly ? '请上传文件' : description}
- </DialogDescription>
- </DialogHeader>
- <div className="space-y-4">
- {/* uploadOnly 模式:只显示上传区域 */}
- {uploadOnly ? (
- <div className="flex items-center justify-center py-8">
- <div className="w-full max-w-md">
- <MinioUploader
- uploadPath={uploadPath}
- accept={accept}
- maxSize={maxSize}
- onUploadSuccess={handleUploadSuccess}
- buttonText="点击或拖拽上传文件"
- size="default"
- displayMode="full"
- showUploadList={true}
- uploadListTitle="上传进度"
- />
- </div>
- </div>
- ) : (
- /* 默认模式:显示文件列表 */
- <div className="space-y-2 max-h-96 overflow-y-auto p-1">
- {isLoading ? (
- <Card>
- <CardContent className="text-center py-8">
- <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
- <p className="text-gray-500 mt-2">加载中...</p>
- </CardContent>
- </Card>
- ) : (
- <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
- {/* 上传区域 - 作为第一项 */}
- <div className="relative cursor-pointer transition-all duration-200">
- <div className="rounded-lg border-2 border-dashed border-gray-300 hover:border-primary transition-colors hover:scale-105">
- <div className="p-2 h-20 flex items-center justify-center">
- <MinioUploader
- uploadPath={uploadPath}
- accept={accept}
- maxSize={maxSize}
- onUploadSuccess={handleUploadSuccess}
- buttonText="上传"
- size="minimal"
- displayMode="card"
- showUploadList={false}
- />
- </div>
- </div>
- <p className="text-xs text-center mt-1 text-muted-foreground">
- 上传新文件
- </p>
- </div>
- {/* 现有文件列表 */}
- {files.map((file) => (
- <div
- key={file.id}
- className={cn(
- "relative cursor-pointer transition-all duration-200",
- "hover:scale-105"
- )}
- onClick={() => handleSelectFile(file)}
- >
- <div
- className={cn(
- "relative rounded-lg overflow-hidden border-2 aspect-square",
- isSelected(file.id)
- ? "border-primary ring-2 ring-primary ring-offset-2"
- : "border-gray-200 hover:border-primary"
- )}
- >
- {file?.type?.startsWith('image/') ? (
- <img
- src={file.fullUrl}
- alt={file.name}
- className="w-full h-full object-cover"
- />
- ) : (
- <div className="w-full h-full flex flex-col items-center justify-center bg-gray-50 p-2">
- {file.type && getFileIcon(file.type)}
- <p className="text-xs text-center mt-1 truncate max-w-full">
- {file.name}
- </p>
- </div>
- )}
- {isSelected(file.id) && (
- <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
- <Check className="h-6 w-6 text-white bg-primary rounded-full p-1" />
- </div>
- )}
- <div className="absolute top-1 right-1">
- <Eye
- className="h-4 w-4 text-white bg-black/50 rounded-full p-0.5 cursor-pointer hover:bg-black/70"
- onClick={(e) => {
- e.stopPropagation();
- window.open(file.fullUrl, '_blank');
- }}
- />
- </div>
- </div>
- <p className="text-xs text-center mt-1 truncate">
- {file.name}
- </p>
- </div>
- ))}
- {/* 空状态 - 当没有文件时显示 */}
- {files.length === 0 && (
- <div className="col-span-full">
- <Card>
- <CardContent className="text-center py-8">
- <div className="flex flex-col items-center">
- <Upload className="h-12 w-12 text-gray-400 mb-4" />
- <p className="text-gray-600">暂无文件</p>
- <p className="text-sm text-gray-500 mt-2">请上传文件</p>
- </div>
- </CardContent>
- </Card>
- </div>
- )}
- </div>
- )}
- </div>
- )}
- </div>
- {/* uploadOnly 模式下不显示确认/取消按钮 */}
- {!uploadOnly && (
- <DialogFooter>
- <Button type="button" variant="outline" onClick={handleCancel}>
- 取消
- </Button>
- <Button
- type="button"
- onClick={handleConfirm}
- disabled={allowMultiple ? localSelectedFiles.length === 0 : !selectedFile}
- >
- {allowMultiple ? `确认选择 (${localSelectedFiles.length})` : '确认选择'}
- </Button>
- </DialogFooter>
- )}
- </DialogContent>
- </Dialog>
- </>
- );
- };
- export default FileSelector;
|