FileSelector.tsx 19 KB

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