FileSelector.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. import React, { useState, useEffect } from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { Button } from '@/client/components/ui/button';
  4. import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/client/components/ui/dialog';
  5. import { Card, CardContent } from '@/client/components/ui/card';
  6. import { toast } from 'sonner';
  7. import { fileClient } from '@/client/api';
  8. import MinioUploader from '@/client/components/MinioUploader';
  9. import { Check, Upload, Eye, X, File as FileIcon, Image as ImageIcon } from 'lucide-react';
  10. import { cn } from '@/client/lib/utils';
  11. import type { InferResponseType } from 'hono/client';
  12. type FileType = InferResponseType<typeof fileClient.$get, 200>['data'][0]
  13. export interface FileSelectorProps {
  14. value?: number | null | number[];
  15. onChange?: (fileId: number | null | number[]) => void;
  16. accept?: string;
  17. maxSize?: number;
  18. uploadPath?: string;
  19. uploadButtonText?: string;
  20. previewSize?: 'small' | 'medium' | 'large';
  21. showPreview?: boolean;
  22. placeholder?: string;
  23. title?: string;
  24. description?: string;
  25. filterType?: 'image' | 'all' | string;
  26. allowMultiple?: boolean;
  27. /** 指定要筛选的上传用户ID,为0或undefined时显示所有用户的文件 */
  28. uploadUserId?: number;
  29. }
  30. export const FileSelector: React.FC<FileSelectorProps> = ({
  31. value,
  32. onChange,
  33. accept = '*/*',
  34. maxSize = 10,
  35. uploadPath = '/files',
  36. uploadButtonText = '上传文件',
  37. previewSize = 'medium',
  38. showPreview = true,
  39. placeholder = '选择文件',
  40. title = '选择文件',
  41. description = '上传新文件或从已有文件中选择',
  42. filterType = 'all',
  43. allowMultiple = false,
  44. uploadUserId = 0,
  45. }) => {
  46. const [isOpen, setIsOpen] = useState(false);
  47. const [selectedFile, setSelectedFile] = useState<FileType | null>(null);
  48. const [localSelectedFiles, setLocalSelectedFiles] = useState<number[]>([]);
  49. // 获取当前选中的文件详情 - 支持单值和数组
  50. const { data: currentFiles } = useQuery<FileType[]>({
  51. queryKey: ['file-details', value, allowMultiple],
  52. queryFn: async (): Promise<FileType[]> => {
  53. if (!value) return [];
  54. // 处理多选模式下的数组值
  55. if (allowMultiple && Array.isArray(value)) {
  56. if (value.length === 0) return [];
  57. // 批量获取多个文件详情
  58. const filePromises = value.map(async (fileId) => {
  59. try {
  60. const response = await fileClient[':id']['$get']({ param: { id: fileId.toString() } });
  61. if (response.status === 200) {
  62. return response.json();
  63. }
  64. return null;
  65. } catch (error) {
  66. console.error(`获取文件 ${fileId} 详情失败:`, error);
  67. return null;
  68. }
  69. });
  70. const files = await Promise.all(filePromises);
  71. return files.filter(file => file !== null);
  72. }
  73. // 处理单选模式下的单值
  74. if (!Array.isArray(value)) {
  75. const response = await fileClient[':id']['$get']({ param: { id: value.toString() } });
  76. if (response.status !== 200) throw new Error('获取文件详情失败');
  77. return [await response.json()];
  78. }
  79. return [];
  80. },
  81. enabled: !!value,
  82. });
  83. // 当对话框打开时,设置当前选中的文件
  84. useEffect(() => {
  85. if (isOpen) {
  86. if (allowMultiple) {
  87. // 在多选模式下,使用 value 数组初始化本地选择
  88. const initialSelection = Array.isArray(value) ? value : [];
  89. setLocalSelectedFiles(initialSelection);
  90. } else if (value && currentFiles && currentFiles.length > 0) {
  91. setSelectedFile(currentFiles[0]);
  92. }
  93. }
  94. }, [isOpen, value, currentFiles, allowMultiple]);
  95. // 获取文件列表
  96. const { data: filesData, isLoading, refetch } = useQuery({
  97. queryKey: ['files-for-selection', filterType, uploadUserId] as const,
  98. queryFn: async () => {
  99. // 构建筛选条件
  100. const filters: any = {};
  101. // 如果指定了上传用户ID,则筛选该用户的文件
  102. if (uploadUserId && uploadUserId > 0) {
  103. filters.uploadUserId = uploadUserId;
  104. }
  105. const response = await fileClient.$get({
  106. query: {
  107. page: 1,
  108. pageSize: 50,
  109. ...(filterType !== 'all' && { keyword: filterType }),
  110. ...(Object.keys(filters).length > 0 && {
  111. filters: JSON.stringify(filters)
  112. })
  113. }
  114. });
  115. if (response.status !== 200) throw new Error('获取文件列表失败');
  116. return response.json();
  117. },
  118. enabled: isOpen,
  119. });
  120. const files = filesData?.data?.filter((f) => {
  121. if (filterType === 'all') return true;
  122. if (filterType === 'image') return f?.type?.startsWith('image/');
  123. return f?.type?.includes(filterType);
  124. }) || [];
  125. const handleSelectFile = (file: FileType) => {
  126. if (allowMultiple) {
  127. setLocalSelectedFiles(prev => {
  128. const newSelection = prev.includes(file.id)
  129. ? prev.filter(id => id !== file.id)
  130. : [...prev, file.id];
  131. return newSelection;
  132. });
  133. } else {
  134. setSelectedFile(prevSelected => {
  135. if (prevSelected?.id === file.id) {
  136. return null;
  137. }
  138. return file;
  139. });
  140. }
  141. };
  142. const handleConfirm = () => {
  143. if (allowMultiple) {
  144. if (onChange) {
  145. onChange(localSelectedFiles);
  146. }
  147. setIsOpen(false);
  148. return;
  149. }
  150. if (!selectedFile) {
  151. toast.warning('请选择一个文件');
  152. return;
  153. }
  154. if (onChange) {
  155. onChange(selectedFile.id);
  156. }
  157. setIsOpen(false);
  158. setSelectedFile(null);
  159. };
  160. const handleCancel = () => {
  161. setIsOpen(false);
  162. setSelectedFile(null);
  163. // 取消时重置为初始的 value 值
  164. const initialSelection = allowMultiple && Array.isArray(value) ? value : [];
  165. setLocalSelectedFiles(initialSelection);
  166. };
  167. const handleUploadSuccess = () => {
  168. toast.success('文件上传成功!请从列表中选择新上传的文件');
  169. refetch();
  170. };
  171. const getPreviewSize = () => {
  172. switch (previewSize) {
  173. case 'small':
  174. return 'h-16 w-16';
  175. case 'medium':
  176. return 'h-24 w-24';
  177. case 'large':
  178. return 'h-32 w-32';
  179. default:
  180. return 'h-24 w-24';
  181. }
  182. };
  183. const getFileIcon = (fileType: string) => {
  184. if (fileType.startsWith('image/')) {
  185. return <ImageIcon className="h-8 w-8 text-gray-400" />;
  186. }
  187. if (fileType.startsWith('video/')) {
  188. return <FileIcon className="h-8 w-8 text-blue-500" />;
  189. }
  190. if (fileType.startsWith('audio/')) {
  191. return <FileIcon className="h-8 w-8 text-green-500" />;
  192. }
  193. if (fileType.includes('pdf')) {
  194. return <FileIcon className="h-8 w-8 text-red-500" />;
  195. }
  196. if (fileType.includes('text')) {
  197. return <FileIcon className="h-8 w-8 text-gray-600" />;
  198. }
  199. return <FileIcon className="h-8 w-8 text-gray-400" />;
  200. };
  201. const handleRemoveFile = (e: React.MouseEvent) => {
  202. e.stopPropagation();
  203. if (allowMultiple && Array.isArray(value)) {
  204. // 在多选模式下,移除所有选中文件
  205. onChange?.([]);
  206. } else {
  207. // 在单选模式下,设置为null
  208. onChange?.(null);
  209. }
  210. };
  211. const isSelected = (fileId: number) => {
  212. if (allowMultiple) {
  213. return localSelectedFiles.includes(fileId);
  214. }
  215. return selectedFile?.id === fileId;
  216. };
  217. return (
  218. <>
  219. <div className="space-y-4">
  220. {showPreview && (
  221. <div className="flex items-start space-x-4">
  222. {/* 预览区域 */}
  223. <div className="flex flex-wrap gap-2">
  224. {allowMultiple && Array.isArray(currentFiles) && currentFiles.length > 0 ? (
  225. // 多选模式下的预览
  226. currentFiles.map((file) => (
  227. <div key={file.id} className="relative group">
  228. <div
  229. className={cn(
  230. getPreviewSize(),
  231. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  232. )}
  233. onClick={() => setIsOpen(true)}
  234. >
  235. {file?.type ? (
  236. <div className="w-full h-full flex items-center justify-center">
  237. {file.type.startsWith('image/') ? (
  238. <img
  239. src={file.fullUrl}
  240. alt={file.name}
  241. className="w-full h-full object-cover"
  242. />
  243. ) : (
  244. <div className="flex flex-col items-center justify-center text-gray-400">
  245. {getFileIcon(file.type)}
  246. <span className="text-xs mt-1 text-center px-1 truncate max-w-full">
  247. {file.name}
  248. </span>
  249. </div>
  250. )}
  251. </div>
  252. ) : (
  253. <div className="flex flex-col items-center justify-center text-gray-400">
  254. <FileIcon className="h-8 w-8 mb-1" />
  255. <span className="text-xs">{placeholder}</span>
  256. </div>
  257. )}
  258. </div>
  259. <button
  260. type="button"
  261. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  262. onClick={(e) => {
  263. e.stopPropagation();
  264. if (allowMultiple && Array.isArray(value)) {
  265. const newValue = value.filter(id => id !== file.id);
  266. onChange?.(newValue);
  267. }
  268. }}
  269. >
  270. <X className="h-3 w-3" />
  271. </button>
  272. </div>
  273. ))
  274. ) : !allowMultiple && currentFiles && currentFiles.length > 0 ? (
  275. // 单选模式下的预览
  276. <div className="relative group">
  277. <div
  278. className={cn(
  279. getPreviewSize(),
  280. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  281. )}
  282. onClick={() => setIsOpen(true)}
  283. >
  284. {currentFiles[0]?.type ? (
  285. <div className="w-full h-full flex items-center justify-center">
  286. {currentFiles[0].type.startsWith('image/') ? (
  287. <img
  288. src={currentFiles[0].fullUrl}
  289. alt={currentFiles[0].name}
  290. className="w-full h-full object-cover"
  291. />
  292. ) : (
  293. <div className="flex flex-col items-center justify-center text-gray-400">
  294. {getFileIcon(currentFiles[0].type)}
  295. <span className="text-xs mt-1 text-center">{currentFiles[0].name}</span>
  296. </div>
  297. )}
  298. </div>
  299. ) : (
  300. <div className="flex flex-col items-center justify-center text-gray-400">
  301. <FileIcon className="h-8 w-8 mb-1" />
  302. <span className="text-xs">{placeholder}</span>
  303. </div>
  304. )}
  305. </div>
  306. {currentFiles[0] && (
  307. <button
  308. type="button"
  309. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  310. onClick={handleRemoveFile}
  311. >
  312. <X className="h-3 w-3" />
  313. </button>
  314. )}
  315. </div>
  316. ) : (
  317. // 没有选中文件时的占位符
  318. <div
  319. className={cn(
  320. getPreviewSize(),
  321. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  322. )}
  323. onClick={() => setIsOpen(true)}
  324. >
  325. <div className="flex flex-col items-center justify-center text-gray-400">
  326. <FileIcon className="h-8 w-8 mb-1" />
  327. <span className="text-xs">{placeholder}</span>
  328. </div>
  329. </div>
  330. )}
  331. </div>
  332. <div className="space-y-2">
  333. <Button
  334. type="button"
  335. variant="outline"
  336. onClick={() => setIsOpen(true)}
  337. className="text-sm"
  338. >
  339. {((allowMultiple && currentFiles && currentFiles.length > 0) ||
  340. (!allowMultiple && currentFiles && currentFiles.length > 0)) ? '更换文件' : placeholder}
  341. </Button>
  342. {!allowMultiple && currentFiles && currentFiles.length > 0 && (
  343. <p className="text-xs text-muted-foreground truncate w-40 sm:w-64">
  344. 当前: {currentFiles[0].name}
  345. </p>
  346. )}
  347. {allowMultiple && currentFiles && currentFiles.length > 0 && (
  348. <p className="text-xs text-muted-foreground">
  349. 已选择 {currentFiles.length} 个文件
  350. </p>
  351. )}
  352. </div>
  353. </div>
  354. )}
  355. {!showPreview && (
  356. <Button
  357. type="button"
  358. variant="outline"
  359. onClick={() => setIsOpen(true)}
  360. className="w-full"
  361. >
  362. {currentFiles ? '更换文件' : placeholder}
  363. </Button>
  364. )}
  365. </div>
  366. <Dialog open={isOpen} onOpenChange={setIsOpen}>
  367. <DialogContent className="max-w-4xl max-h-[90vh]">
  368. <DialogHeader>
  369. <DialogTitle>{title}</DialogTitle>
  370. <DialogDescription>
  371. {description}
  372. </DialogDescription>
  373. </DialogHeader>
  374. <div className="space-y-4">
  375. {/* 文件列表 */}
  376. <div className="space-y-2 max-h-96 overflow-y-auto p-1">
  377. {isLoading ? (
  378. <Card>
  379. <CardContent className="text-center py-8">
  380. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
  381. <p className="text-gray-500 mt-2">加载中...</p>
  382. </CardContent>
  383. </Card>
  384. ) : (
  385. <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
  386. {/* 上传区域 - 作为第一项 */}
  387. <div className="relative cursor-pointer transition-all duration-200">
  388. <div className="rounded-lg border-2 border-dashed border-gray-300 hover:border-primary transition-colors hover:scale-105">
  389. <div className="p-2 h-20 flex items-center justify-center">
  390. <MinioUploader
  391. uploadPath={uploadPath}
  392. accept={accept}
  393. maxSize={maxSize}
  394. onUploadSuccess={handleUploadSuccess}
  395. buttonText="上传"
  396. size="minimal"
  397. displayMode="card"
  398. showUploadList={false}
  399. />
  400. </div>
  401. </div>
  402. <p className="text-xs text-center mt-1 text-muted-foreground">
  403. 上传新文件
  404. </p>
  405. </div>
  406. {/* 现有文件列表 */}
  407. {files.map((file) => (
  408. <div
  409. key={file.id}
  410. className={cn(
  411. "relative cursor-pointer transition-all duration-200",
  412. "hover:scale-105"
  413. )}
  414. onClick={() => handleSelectFile(file)}
  415. >
  416. <div
  417. className={cn(
  418. "relative rounded-lg overflow-hidden border-2 aspect-square",
  419. isSelected(file.id)
  420. ? "border-primary ring-2 ring-primary ring-offset-2"
  421. : "border-gray-200 hover:border-primary"
  422. )}
  423. >
  424. {file?.type?.startsWith('image/') ? (
  425. <img
  426. src={file.fullUrl}
  427. alt={file.name}
  428. className="w-full h-full object-cover"
  429. />
  430. ) : (
  431. <div className="w-full h-full flex flex-col items-center justify-center bg-gray-50 p-2">
  432. {file.type && getFileIcon(file.type)}
  433. <p className="text-xs text-center mt-1 truncate max-w-full">
  434. {file.name}
  435. </p>
  436. </div>
  437. )}
  438. {isSelected(file.id) && (
  439. <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
  440. <Check className="h-6 w-6 text-white bg-primary rounded-full p-1" />
  441. </div>
  442. )}
  443. <div className="absolute top-1 right-1">
  444. <Eye
  445. className="h-4 w-4 text-white bg-black/50 rounded-full p-0.5 cursor-pointer hover:bg-black/70"
  446. onClick={(e) => {
  447. e.stopPropagation();
  448. window.open(file.fullUrl, '_blank');
  449. }}
  450. />
  451. </div>
  452. </div>
  453. <p className="text-xs text-center mt-1 truncate">
  454. {file.name}
  455. </p>
  456. </div>
  457. ))}
  458. {/* 空状态 - 当没有文件时显示 */}
  459. {files.length === 0 && (
  460. <div className="col-span-full">
  461. <Card>
  462. <CardContent className="text-center py-8">
  463. <div className="flex flex-col items-center">
  464. <Upload className="h-12 w-12 text-gray-400 mb-4" />
  465. <p className="text-gray-600">暂无文件</p>
  466. <p className="text-sm text-gray-500 mt-2">请上传文件</p>
  467. </div>
  468. </CardContent>
  469. </Card>
  470. </div>
  471. )}
  472. </div>
  473. )}
  474. </div>
  475. </div>
  476. <DialogFooter>
  477. <Button type="button" variant="outline" onClick={handleCancel}>
  478. 取消
  479. </Button>
  480. <Button
  481. type="button"
  482. onClick={handleConfirm}
  483. disabled={allowMultiple ? localSelectedFiles.length === 0 : !selectedFile}
  484. >
  485. {allowMultiple ? `确认选择 (${localSelectedFiles.length})` : '确认选择'}
  486. </Button>
  487. </DialogFooter>
  488. </DialogContent>
  489. </Dialog>
  490. </>
  491. );
  492. };
  493. export default FileSelector;