FileSelector.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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/admin/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. 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 fileClient[':id']['$get']({ param: { id: Number(fileId) } });
  56. if (response.status === 200) {
  57. return response.json();
  58. }
  59. return null;
  60. } catch (error) {
  61. console.error(`获取文件 ${fileId} 详情失败:`, error);
  62. return null;
  63. }
  64. });
  65. const files = await Promise.all(filePromises);
  66. return files.filter(file => file !== null);
  67. }
  68. // 处理单选模式下的单值
  69. if (!Array.isArray(value)) {
  70. const response = await fileClient[':id']['$get']({ param: { id: Number(value) } });
  71. if (response.status !== 200) throw new Error('获取文件详情失败');
  72. return [await response.json()];
  73. }
  74. return [];
  75. },
  76. enabled: !!value,
  77. });
  78. // 当对话框打开时,设置当前选中的文件
  79. useEffect(() => {
  80. if (isOpen) {
  81. if (allowMultiple) {
  82. // 在多选模式下,使用 value 数组初始化本地选择
  83. const initialSelection = Array.isArray(value) ? value : [];
  84. setLocalSelectedFiles(initialSelection);
  85. } else if (value && currentFiles && currentFiles.length > 0) {
  86. setSelectedFile(currentFiles[0]);
  87. }
  88. }
  89. }, [isOpen, value, currentFiles, allowMultiple]);
  90. // 获取文件列表
  91. const { data: filesData, isLoading, refetch } = useQuery({
  92. queryKey: ['files-for-selection', filterType] as const,
  93. queryFn: async () => {
  94. const response = await fileClient.$get({
  95. query: {
  96. page: 1,
  97. pageSize: 50,
  98. ...(filterType !== 'all' && { keyword: filterType })
  99. }
  100. });
  101. if (response.status !== 200) throw new Error('获取文件列表失败');
  102. return response.json();
  103. },
  104. enabled: isOpen,
  105. });
  106. const files = filesData?.data?.filter((f) => {
  107. if (filterType === 'all') return true;
  108. if (filterType === 'image') return f?.type?.startsWith('image/');
  109. return f?.type?.includes(filterType);
  110. }) || [];
  111. const handleSelectFile = (file: FileType) => {
  112. if (allowMultiple) {
  113. setLocalSelectedFiles(prev => {
  114. const newSelection = prev.includes(file.id)
  115. ? prev.filter(id => id !== file.id)
  116. : [...prev, file.id];
  117. return newSelection;
  118. });
  119. } else {
  120. setSelectedFile(prevSelected => {
  121. if (prevSelected?.id === file.id) {
  122. return null;
  123. }
  124. return file;
  125. });
  126. }
  127. };
  128. const handleConfirm = () => {
  129. if (allowMultiple) {
  130. if (onChange) {
  131. onChange(localSelectedFiles);
  132. }
  133. setIsOpen(false);
  134. return;
  135. }
  136. if (!selectedFile) {
  137. toast.warning('请选择一个文件');
  138. return;
  139. }
  140. if (onChange) {
  141. onChange(selectedFile.id);
  142. }
  143. setIsOpen(false);
  144. setSelectedFile(null);
  145. };
  146. const handleCancel = () => {
  147. setIsOpen(false);
  148. setSelectedFile(null);
  149. // 取消时重置为初始的 value 值
  150. const initialSelection = allowMultiple && Array.isArray(value) ? value : [];
  151. setLocalSelectedFiles(initialSelection);
  152. };
  153. const handleUploadSuccess = () => {
  154. toast.success('文件上传成功!请从列表中选择新上传的文件');
  155. refetch();
  156. };
  157. const getPreviewSize = () => {
  158. switch (previewSize) {
  159. case 'small':
  160. return 'h-16 w-16';
  161. case 'medium':
  162. return 'h-24 w-24';
  163. case 'large':
  164. return 'h-32 w-32';
  165. default:
  166. return 'h-24 w-24';
  167. }
  168. };
  169. const getFileIcon = (fileType: string) => {
  170. if (fileType.startsWith('image/')) {
  171. return <ImageIcon className="h-8 w-8 text-gray-400" />;
  172. }
  173. if (fileType.startsWith('video/')) {
  174. return <FileIcon className="h-8 w-8 text-blue-500" />;
  175. }
  176. if (fileType.startsWith('audio/')) {
  177. return <FileIcon className="h-8 w-8 text-green-500" />;
  178. }
  179. if (fileType.includes('pdf')) {
  180. return <FileIcon className="h-8 w-8 text-red-500" />;
  181. }
  182. if (fileType.includes('text')) {
  183. return <FileIcon className="h-8 w-8 text-gray-600" />;
  184. }
  185. return <FileIcon className="h-8 w-8 text-gray-400" />;
  186. };
  187. const handleRemoveFile = (e: React.MouseEvent) => {
  188. e.stopPropagation();
  189. if (allowMultiple && Array.isArray(value)) {
  190. // 在多选模式下,移除所有选中文件
  191. onChange?.([]);
  192. } else {
  193. // 在单选模式下,设置为null
  194. onChange?.(null);
  195. }
  196. };
  197. const isSelected = (fileId: number) => {
  198. if (allowMultiple) {
  199. return localSelectedFiles.includes(fileId);
  200. }
  201. return selectedFile?.id === fileId;
  202. };
  203. return (
  204. <>
  205. <div className="space-y-4">
  206. {showPreview && (
  207. <div className="flex items-start space-x-4">
  208. {/* 预览区域 */}
  209. <div className="flex flex-wrap gap-2">
  210. {allowMultiple && Array.isArray(currentFiles) && currentFiles.length > 0 ? (
  211. // 多选模式下的预览
  212. currentFiles.map((file) => (
  213. <div key={file.id} className="relative group">
  214. <div
  215. className={cn(
  216. getPreviewSize(),
  217. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  218. )}
  219. onClick={() => setIsOpen(true)}
  220. >
  221. {file?.type ? (
  222. <div className="w-full h-full flex items-center justify-center">
  223. {file.type.startsWith('image/') ? (
  224. <img
  225. src={file.fullUrl}
  226. alt={file.name}
  227. className="w-full h-full object-cover"
  228. />
  229. ) : (
  230. <div className="flex flex-col items-center justify-center text-gray-400">
  231. {getFileIcon(file.type)}
  232. <span className="text-xs mt-1 text-center px-1 truncate max-w-full">
  233. {file.name}
  234. </span>
  235. </div>
  236. )}
  237. </div>
  238. ) : (
  239. <div className="flex flex-col items-center justify-center text-gray-400">
  240. <FileIcon className="h-8 w-8 mb-1" />
  241. <span className="text-xs">{placeholder}</span>
  242. </div>
  243. )}
  244. </div>
  245. <button
  246. type="button"
  247. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  248. onClick={(e) => {
  249. e.stopPropagation();
  250. if (allowMultiple && Array.isArray(value)) {
  251. const newValue = value.filter(id => id !== file.id);
  252. onChange?.(newValue);
  253. }
  254. }}
  255. >
  256. <X className="h-3 w-3" />
  257. </button>
  258. </div>
  259. ))
  260. ) : !allowMultiple && currentFiles && currentFiles.length > 0 ? (
  261. // 单选模式下的预览
  262. <div className="relative group">
  263. <div
  264. className={cn(
  265. getPreviewSize(),
  266. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  267. )}
  268. onClick={() => setIsOpen(true)}
  269. >
  270. {currentFiles[0]?.type ? (
  271. <div className="w-full h-full flex items-center justify-center">
  272. {currentFiles[0].type.startsWith('image/') ? (
  273. <img
  274. src={currentFiles[0].fullUrl}
  275. alt={currentFiles[0].name}
  276. className="w-full h-full object-cover"
  277. />
  278. ) : (
  279. <div className="flex flex-col items-center justify-center text-gray-400">
  280. {getFileIcon(currentFiles[0].type)}
  281. <span className="text-xs mt-1 text-center">{currentFiles[0].name}</span>
  282. </div>
  283. )}
  284. </div>
  285. ) : (
  286. <div className="flex flex-col items-center justify-center text-gray-400">
  287. <FileIcon className="h-8 w-8 mb-1" />
  288. <span className="text-xs">{placeholder}</span>
  289. </div>
  290. )}
  291. </div>
  292. {currentFiles[0] && (
  293. <button
  294. type="button"
  295. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  296. onClick={handleRemoveFile}
  297. >
  298. <X className="h-3 w-3" />
  299. </button>
  300. )}
  301. </div>
  302. ) : (
  303. // 没有选中文件时的占位符
  304. <div
  305. className={cn(
  306. getPreviewSize(),
  307. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  308. )}
  309. onClick={() => setIsOpen(true)}
  310. >
  311. <div className="flex flex-col items-center justify-center text-gray-400">
  312. <FileIcon className="h-8 w-8 mb-1" />
  313. <span className="text-xs">{placeholder}</span>
  314. </div>
  315. </div>
  316. )}
  317. </div>
  318. <div className="space-y-2">
  319. <Button
  320. type="button"
  321. variant="outline"
  322. onClick={() => setIsOpen(true)}
  323. className="text-sm"
  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]">
  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;