FileSelector.tsx 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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. * 仅上传模式 - 只显示上传区域,不显示现有文件列表
  28. * @default false
  29. *
  30. * 当设置为 true 时:
  31. * - 对话框只显示上传区域(MinioUploader)
  32. * - 不显示现有文件列表
  33. * - 不调用文件列表查询 API(性能优化)
  34. * - 上传成功后自动选中该文件并关闭对话框,直接返回 fileId
  35. *
  36. * 适用场景:需要快速上传文件而不需要从现有文件中选择时,
  37. * 如残疾人上传资料时避免加载大量缩略图导致的性能问题
  38. */
  39. uploadOnly?: boolean;
  40. }
  41. export const FileSelector: React.FC<FileSelectorProps> = ({
  42. value,
  43. onChange,
  44. accept = '*/*',
  45. maxSize = 10,
  46. uploadPath = '/files',
  47. previewSize = 'medium',
  48. showPreview = true,
  49. placeholder = '选择文件',
  50. title = '选择文件',
  51. description = '上传新文件或从已有文件中选择',
  52. filterType = 'all',
  53. allowMultiple = false,
  54. uploadOnly = false,
  55. }) => {
  56. const [isOpen, setIsOpen] = useState(false);
  57. const [selectedFile, setSelectedFile] = useState<FileType | null>(null);
  58. const [localSelectedFiles, setLocalSelectedFiles] = useState<number[]>([]);
  59. // 获取当前选中的文件详情 - 支持单值和数组
  60. const { data: currentFiles } = useQuery<FileType[]>({
  61. queryKey: ['file-details', value, allowMultiple],
  62. queryFn: async (): Promise<FileType[]> => {
  63. if (!value) return [];
  64. // 处理多选模式下的数组值
  65. if (allowMultiple && Array.isArray(value)) {
  66. if (value.length === 0) return [];
  67. // 批量获取多个文件详情
  68. const filePromises = value.map(async (fileId) => {
  69. try {
  70. const response = await fileClientManager.get()[':id']['$get']({ param: { id: Number(fileId) } });
  71. if (response.status === 200) {
  72. return response.json();
  73. }
  74. return null;
  75. } catch {
  76. return null;
  77. }
  78. });
  79. const files = await Promise.all(filePromises);
  80. return files.filter(file => file !== null);
  81. }
  82. // 处理单选模式下的单值
  83. if (!Array.isArray(value)) {
  84. const response = await fileClientManager.get()[':id']['$get']({ param: { id: Number(value) } });
  85. if (response.status !== 200) throw new Error('获取文件详情失败');
  86. return [await response.json()];
  87. }
  88. return [];
  89. },
  90. enabled: !!value,
  91. });
  92. // 当对话框打开时,设置当前选中的文件
  93. useEffect(() => {
  94. if (isOpen) {
  95. if (allowMultiple) {
  96. // 在多选模式下,使用 value 数组初始化本地选择
  97. const initialSelection = Array.isArray(value) ? value : [];
  98. setLocalSelectedFiles(initialSelection);
  99. } else if (value && currentFiles && currentFiles.length > 0) {
  100. setSelectedFile(currentFiles[0]);
  101. }
  102. }
  103. }, [isOpen, value, currentFiles, allowMultiple]);
  104. // 获取文件列表 - uploadOnly 模式下禁用查询以提高性能
  105. const { data: filesData, isLoading, refetch } = useQuery({
  106. queryKey: ['files-for-selection', filterType] as const,
  107. queryFn: async () => {
  108. const response = await fileClientManager.get().index.$get({
  109. query: {
  110. page: 1,
  111. pageSize: 50,
  112. ...(filterType !== 'all' && { keyword: filterType })
  113. }
  114. });
  115. if (response.status !== 200) throw new Error('获取文件列表失败');
  116. return response.json();
  117. },
  118. enabled: isOpen && !uploadOnly, // uploadOnly 模式下不执行查询
  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 = async (_fileKey: string, _fileUrl: string, file: File) => {
  168. if (uploadOnly) {
  169. // uploadOnly 模式:上传成功后自动获取 fileId 并返回
  170. try {
  171. // 记录上传开始时间
  172. const uploadStartTime = Date.now();
  173. // 获取刚上传的文件的 ID(通过文件名、大小和时间戳匹配)
  174. const response = await fileClientManager.get().index.$get({
  175. query: {
  176. page: 1,
  177. pageSize: 50, // 获取更多结果以提高匹配概率
  178. }
  179. });
  180. if (response.status === 200) {
  181. const data = await response.json();
  182. // 多重匹配策略,提高准确性:
  183. // 1. 首先通过文件名和大小匹配
  184. // 2. 验证上传时间在最近 30 秒内
  185. // 3. 如果有多个匹配,选择最新的
  186. const matchCandidates = data.data?.filter((f: FileType) => {
  187. // 基础匹配:文件名和大小
  188. if (f.name !== file.name || f.size !== file.size) {
  189. return false;
  190. }
  191. // 时间验证:上传时间在最近 30 秒内(避免匹配旧文件)
  192. const fileUploadTime = new Date(f.uploadTime || '').getTime();
  193. const timeDiff = uploadStartTime - fileUploadTime;
  194. return timeDiff >= 0 && timeDiff < 30000; // 30 秒内
  195. }) || [];
  196. if (matchCandidates.length > 0) {
  197. // 选择最新的文件(按 uploadTime 降序排序)
  198. const uploadedFile = matchCandidates.sort((a: FileType, b: FileType) => {
  199. const timeA = new Date(a.uploadTime || '').getTime();
  200. const timeB = new Date(b.uploadTime || '').getTime();
  201. return timeB - timeA; // 降序
  202. })[0];
  203. // 直接返回 fileId 并关闭对话框
  204. if (allowMultiple) {
  205. onChange?.([uploadedFile.id]);
  206. } else {
  207. onChange?.(uploadedFile.id);
  208. }
  209. setIsOpen(false);
  210. toast.success('文件上传成功!');
  211. return;
  212. }
  213. }
  214. // 如果找不到文件,提示用户
  215. toast.error('无法获取上传的文件信息');
  216. } catch (error) {
  217. console.error('获取上传文件信息失败:', error);
  218. toast.error('获取上传文件信息失败');
  219. }
  220. } else {
  221. // 默认模式:提示用户从列表中选择
  222. toast.success('文件上传成功!请从列表中选择新上传的文件');
  223. refetch();
  224. }
  225. };
  226. const getPreviewSize = () => {
  227. switch (previewSize) {
  228. case 'small':
  229. return 'h-16 w-16';
  230. case 'medium':
  231. return 'h-24 w-24';
  232. case 'large':
  233. return 'h-32 w-32';
  234. default:
  235. return 'h-24 w-24';
  236. }
  237. };
  238. const getFileIcon = (fileType: string) => {
  239. if (fileType.startsWith('image/')) {
  240. return <ImageIcon className="h-8 w-8 text-gray-400" />;
  241. }
  242. if (fileType.startsWith('video/')) {
  243. return <FileIcon className="h-8 w-8 text-blue-500" />;
  244. }
  245. if (fileType.startsWith('audio/')) {
  246. return <FileIcon className="h-8 w-8 text-green-500" />;
  247. }
  248. if (fileType.includes('pdf')) {
  249. return <FileIcon className="h-8 w-8 text-red-500" />;
  250. }
  251. if (fileType.includes('text')) {
  252. return <FileIcon className="h-8 w-8 text-gray-600" />;
  253. }
  254. return <FileIcon className="h-8 w-8 text-gray-400" />;
  255. };
  256. const handleRemoveFile = (e: React.MouseEvent) => {
  257. e.stopPropagation();
  258. if (allowMultiple && Array.isArray(value)) {
  259. // 在多选模式下,移除所有选中文件
  260. onChange?.([]);
  261. } else {
  262. // 在单选模式下,设置为null
  263. onChange?.(null);
  264. }
  265. };
  266. const isSelected = (fileId: number) => {
  267. if (allowMultiple) {
  268. return localSelectedFiles.includes(fileId);
  269. }
  270. return selectedFile?.id === fileId;
  271. };
  272. return (
  273. <>
  274. <div className="space-y-4">
  275. {showPreview && (
  276. <div className="flex items-start space-x-4">
  277. {/* 预览区域 */}
  278. <div className="flex flex-wrap gap-2">
  279. {allowMultiple && Array.isArray(currentFiles) && currentFiles.length > 0 ? (
  280. // 多选模式下的预览
  281. currentFiles.map((file) => (
  282. <div key={file.id} className="relative group">
  283. <div
  284. className={cn(
  285. getPreviewSize(),
  286. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  287. )}
  288. onClick={() => setIsOpen(true)}
  289. >
  290. {file?.type ? (
  291. <div className="w-full h-full flex items-center justify-center">
  292. {file.type.startsWith('image/') ? (
  293. <img
  294. src={file.fullUrl}
  295. alt={file.name}
  296. className="w-full h-full object-cover"
  297. />
  298. ) : (
  299. <div className="flex flex-col items-center justify-center text-gray-400">
  300. {getFileIcon(file.type)}
  301. <span className="text-xs mt-1 text-center px-1 truncate max-w-full">
  302. {file.name}
  303. </span>
  304. </div>
  305. )}
  306. </div>
  307. ) : (
  308. <div className="flex flex-col items-center justify-center text-gray-400">
  309. <FileIcon className="h-8 w-8 mb-1" />
  310. <span className="text-xs">{placeholder}</span>
  311. </div>
  312. )}
  313. </div>
  314. <button
  315. type="button"
  316. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  317. onClick={(e) => {
  318. e.stopPropagation();
  319. if (allowMultiple && Array.isArray(value)) {
  320. const newValue = value.filter(id => id !== file.id);
  321. onChange?.(newValue);
  322. }
  323. }}
  324. >
  325. <X className="h-3 w-3" />
  326. </button>
  327. </div>
  328. ))
  329. ) : !allowMultiple && currentFiles && currentFiles.length > 0 ? (
  330. // 单选模式下的预览
  331. <div className="relative group">
  332. <div
  333. className={cn(
  334. getPreviewSize(),
  335. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  336. )}
  337. onClick={() => setIsOpen(true)}
  338. >
  339. {currentFiles[0]?.type ? (
  340. <div className="w-full h-full flex items-center justify-center">
  341. {currentFiles[0].type.startsWith('image/') ? (
  342. <img
  343. src={currentFiles[0].fullUrl}
  344. alt={currentFiles[0].name}
  345. className="w-full h-full object-cover"
  346. />
  347. ) : (
  348. <div className="flex flex-col items-center justify-center text-gray-400">
  349. {getFileIcon(currentFiles[0].type)}
  350. <span className="text-xs mt-1 text-center">{currentFiles[0].name}</span>
  351. </div>
  352. )}
  353. </div>
  354. ) : (
  355. <div className="flex flex-col items-center justify-center text-gray-400">
  356. <FileIcon className="h-8 w-8 mb-1" />
  357. <span className="text-xs">{placeholder}</span>
  358. </div>
  359. )}
  360. </div>
  361. {currentFiles[0] && (
  362. <button
  363. type="button"
  364. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  365. onClick={handleRemoveFile}
  366. >
  367. <X className="h-3 w-3" />
  368. </button>
  369. )}
  370. </div>
  371. ) : (
  372. // 没有选中文件时的占位符
  373. <div
  374. className={cn(
  375. getPreviewSize(),
  376. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  377. )}
  378. onClick={() => setIsOpen(true)}
  379. >
  380. <div className="flex flex-col items-center justify-center text-gray-400">
  381. <FileIcon className="h-8 w-8 mb-1" />
  382. <span className="text-xs">{placeholder}</span>
  383. </div>
  384. </div>
  385. )}
  386. </div>
  387. <div className="space-y-2">
  388. <Button
  389. type="button"
  390. variant="outline"
  391. onClick={() => setIsOpen(true)}
  392. className="text-sm"
  393. data-testid="file-selector-button"
  394. >
  395. {((allowMultiple && currentFiles && currentFiles.length > 0) ||
  396. (!allowMultiple && currentFiles && currentFiles.length > 0)) ? '更换文件' : placeholder}
  397. </Button>
  398. {!allowMultiple && currentFiles && currentFiles.length > 0 && (
  399. <p className="text-xs text-muted-foreground truncate w-40 sm:w-64">
  400. 当前: {currentFiles[0].name}
  401. </p>
  402. )}
  403. {allowMultiple && currentFiles && currentFiles.length > 0 && (
  404. <p className="text-xs text-muted-foreground">
  405. 已选择 {currentFiles.length} 个文件
  406. </p>
  407. )}
  408. </div>
  409. </div>
  410. )}
  411. {!showPreview && (
  412. <Button
  413. type="button"
  414. variant="outline"
  415. onClick={() => setIsOpen(true)}
  416. className="w-full"
  417. >
  418. {currentFiles ? '更换文件' : placeholder}
  419. </Button>
  420. )}
  421. </div>
  422. <Dialog open={isOpen} onOpenChange={setIsOpen}>
  423. <DialogContent className="max-w-4xl max-h-[90vh]" data-testid="file-selector-dialog">
  424. <DialogHeader>
  425. <DialogTitle>{title}</DialogTitle>
  426. <DialogDescription>
  427. {uploadOnly ? '请上传文件' : description}
  428. </DialogDescription>
  429. </DialogHeader>
  430. <div className="space-y-4">
  431. {/* uploadOnly 模式:只显示上传区域 */}
  432. {uploadOnly ? (
  433. <div className="flex items-center justify-center py-8">
  434. <div className="w-full max-w-md">
  435. <MinioUploader
  436. uploadPath={uploadPath}
  437. accept={accept}
  438. maxSize={maxSize}
  439. onUploadSuccess={handleUploadSuccess}
  440. buttonText="点击或拖拽上传文件"
  441. size="default"
  442. displayMode="full"
  443. showUploadList={true}
  444. uploadListTitle="上传进度"
  445. />
  446. </div>
  447. </div>
  448. ) : (
  449. /* 默认模式:显示文件列表 */
  450. <div className="space-y-2 max-h-96 overflow-y-auto p-1">
  451. {isLoading ? (
  452. <Card>
  453. <CardContent className="text-center py-8">
  454. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
  455. <p className="text-gray-500 mt-2">加载中...</p>
  456. </CardContent>
  457. </Card>
  458. ) : (
  459. <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
  460. {/* 上传区域 - 作为第一项 */}
  461. <div className="relative cursor-pointer transition-all duration-200">
  462. <div className="rounded-lg border-2 border-dashed border-gray-300 hover:border-primary transition-colors hover:scale-105">
  463. <div className="p-2 h-20 flex items-center justify-center">
  464. <MinioUploader
  465. uploadPath={uploadPath}
  466. accept={accept}
  467. maxSize={maxSize}
  468. onUploadSuccess={handleUploadSuccess}
  469. buttonText="上传"
  470. size="minimal"
  471. displayMode="card"
  472. showUploadList={false}
  473. />
  474. </div>
  475. </div>
  476. <p className="text-xs text-center mt-1 text-muted-foreground">
  477. 上传新文件
  478. </p>
  479. </div>
  480. {/* 现有文件列表 */}
  481. {files.map((file) => (
  482. <div
  483. key={file.id}
  484. className={cn(
  485. "relative cursor-pointer transition-all duration-200",
  486. "hover:scale-105"
  487. )}
  488. onClick={() => handleSelectFile(file)}
  489. >
  490. <div
  491. className={cn(
  492. "relative rounded-lg overflow-hidden border-2 aspect-square",
  493. isSelected(file.id)
  494. ? "border-primary ring-2 ring-primary ring-offset-2"
  495. : "border-gray-200 hover:border-primary"
  496. )}
  497. >
  498. {file?.type?.startsWith('image/') ? (
  499. <img
  500. src={file.fullUrl}
  501. alt={file.name}
  502. className="w-full h-full object-cover"
  503. />
  504. ) : (
  505. <div className="w-full h-full flex flex-col items-center justify-center bg-gray-50 p-2">
  506. {file.type && getFileIcon(file.type)}
  507. <p className="text-xs text-center mt-1 truncate max-w-full">
  508. {file.name}
  509. </p>
  510. </div>
  511. )}
  512. {isSelected(file.id) && (
  513. <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
  514. <Check className="h-6 w-6 text-white bg-primary rounded-full p-1" />
  515. </div>
  516. )}
  517. <div className="absolute top-1 right-1">
  518. <Eye
  519. className="h-4 w-4 text-white bg-black/50 rounded-full p-0.5 cursor-pointer hover:bg-black/70"
  520. onClick={(e) => {
  521. e.stopPropagation();
  522. window.open(file.fullUrl, '_blank');
  523. }}
  524. />
  525. </div>
  526. </div>
  527. <p className="text-xs text-center mt-1 truncate">
  528. {file.name}
  529. </p>
  530. </div>
  531. ))}
  532. {/* 空状态 - 当没有文件时显示 */}
  533. {files.length === 0 && (
  534. <div className="col-span-full">
  535. <Card>
  536. <CardContent className="text-center py-8">
  537. <div className="flex flex-col items-center">
  538. <Upload className="h-12 w-12 text-gray-400 mb-4" />
  539. <p className="text-gray-600">暂无文件</p>
  540. <p className="text-sm text-gray-500 mt-2">请上传文件</p>
  541. </div>
  542. </CardContent>
  543. </Card>
  544. </div>
  545. )}
  546. </div>
  547. )}
  548. </div>
  549. )}
  550. </div>
  551. {/* uploadOnly 模式下不显示确认/取消按钮 */}
  552. {!uploadOnly && (
  553. <DialogFooter>
  554. <Button type="button" variant="outline" onClick={handleCancel}>
  555. 取消
  556. </Button>
  557. <Button
  558. type="button"
  559. onClick={handleConfirm}
  560. disabled={allowMultiple ? localSelectedFiles.length === 0 : !selectedFile}
  561. >
  562. {allowMultiple ? `确认选择 (${localSelectedFiles.length})` : '确认选择'}
  563. </Button>
  564. </DialogFooter>
  565. )}
  566. </DialogContent>
  567. </Dialog>
  568. </>
  569. );
  570. };
  571. export default FileSelector;