FileSelector.tsx 19 KB

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