2
0

FilePreview.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import React from 'react';
  2. import { useQuery } from '@tanstack/react-query';
  3. import { fileClient } from '@/client/api';
  4. import type { InferResponseType } from 'hono/client';
  5. import { Eye, FileText, Image as ImageIcon } from 'lucide-react';
  6. import { Skeleton } from '@/client/components/ui/skeleton';
  7. import { Card, CardContent } from '@/client/components/ui/card';
  8. import { Badge } from '@/client/components/ui/badge';
  9. import { Button } from '@/client/components/ui/button';
  10. import { toast } from 'sonner';
  11. // 定义文件类型
  12. type FileItem = InferResponseType<typeof fileClient[':id']['$get'], 200>;
  13. interface FilePreviewItemProps {
  14. file: FileItem;
  15. size: 'small' | 'medium' | 'large';
  16. index?: number;
  17. total?: number;
  18. onClick?: (file: FileItem) => void;
  19. }
  20. const FilePreviewItem: React.FC<FilePreviewItemProps> = ({
  21. file,
  22. size,
  23. index,
  24. total,
  25. onClick
  26. }) => {
  27. const getSize = () => {
  28. switch (size) {
  29. case 'small':
  30. return { width: 45, height: 45 };
  31. case 'medium':
  32. return { width: 80, height: 80 };
  33. case 'large':
  34. return { width: 120, height: 120 };
  35. default:
  36. return { width: 80, height: 80 };
  37. }
  38. };
  39. const { width, height } = getSize();
  40. const isImage = file.type?.startsWith('image/');
  41. const isVideo = file.type?.startsWith('video/');
  42. const handlePreview = () => {
  43. if (onClick) {
  44. onClick(file);
  45. } else if (isImage || isVideo) {
  46. window.open(file.fullUrl, '_blank');
  47. } else {
  48. toast.warning('该文件类型不支持预览');
  49. }
  50. };
  51. // 获取文件图标
  52. const getFileIcon = (type?: string) => {
  53. if (!type) return <FileText className="h-8 w-8 text-gray-400" />;
  54. if (type.startsWith('image/')) {
  55. return <ImageIcon className="h-8 w-8 text-blue-500" />;
  56. } else if (type.startsWith('video/')) {
  57. return <FileText className="h-8 w-8 text-red-500" />;
  58. } else if (type.startsWith('audio/')) {
  59. return <FileText className="h-8 w-8 text-purple-500" />;
  60. } else if (type.includes('pdf')) {
  61. return <FileText className="h-8 w-8 text-red-500" />;
  62. } else if (type.includes('word')) {
  63. return <FileText className="h-8 w-8 text-blue-600" />;
  64. } else if (type.includes('excel') || type.includes('sheet')) {
  65. return <FileText className="h-8 w-8 text-green-500" />;
  66. } else {
  67. return <FileText className="h-8 w-8 text-gray-500" />;
  68. }
  69. };
  70. // 获取文件类型标签
  71. const getFileTypeBadge = (type: string) => {
  72. if (type.startsWith('image/')) {
  73. return { text: '图片', color: 'bg-blue-100 text-blue-800' };
  74. } else if (type.startsWith('video/')) {
  75. return { text: '视频', color: 'bg-red-100 text-red-800' };
  76. } else if (type.startsWith('audio/')) {
  77. return { text: '音频', color: 'bg-purple-100 text-purple-800' };
  78. } else if (type.includes('pdf')) {
  79. return { text: 'PDF', color: 'bg-red-100 text-red-800' };
  80. } else if (type.includes('word')) {
  81. return { text: '文档', color: 'bg-blue-100 text-blue-800' };
  82. } else if (type.includes('excel') || type.includes('sheet')) {
  83. return { text: '表格', color: 'bg-green-100 text-green-800' };
  84. } else {
  85. return { text: '文件', color: 'bg-gray-100 text-gray-800' };
  86. }
  87. };
  88. return (
  89. <div
  90. className="relative group cursor-pointer"
  91. style={{ width, height }}
  92. onClick={handlePreview}
  93. >
  94. {/* 文件预览容器 */}
  95. <div className={`
  96. relative overflow-hidden rounded-lg border transition-all duration-200
  97. ${isImage ? 'border-gray-200' : 'border-gray-300 bg-gray-50'}
  98. group-hover:shadow-md group-hover:border-primary
  99. `}>
  100. {isImage ? (
  101. // 图片预览
  102. <img
  103. src={file.fullUrl}
  104. alt={file.name}
  105. className="w-full h-full object-cover"
  106. loading="lazy"
  107. />
  108. ) : (
  109. // 非图片文件预览
  110. <div className="w-full h-full flex flex-col items-center justify-center">
  111. {getFileIcon(file.type)}
  112. <span className="text-xs text-center mt-1 px-1 truncate max-w-full">
  113. {file.name.length > 8 ? `${file.name.substring(0, 6)}...` : file.name}
  114. </span>
  115. </div>
  116. )}
  117. {/* 悬停遮罩 */}
  118. <div className={`
  119. absolute inset-0 bg-black/60 flex flex-col items-center justify-center
  120. opacity-0 group-hover:opacity-100 transition-opacity duration-200
  121. text-white text-xs
  122. `}>
  123. <Eye className="h-4 w-4 mb-1" />
  124. <span>{isImage || isVideo ? '预览' : '查看'}</span>
  125. </div>
  126. {/* 序号标记 */}
  127. {index !== undefined && total !== undefined && total > 1 && (
  128. <div className={`
  129. absolute top-1 right-1 bg-black/70 text-white text-xs
  130. px-1.5 py-0.5 rounded
  131. `}>
  132. {index + 1}
  133. </div>
  134. )}
  135. </div>
  136. {/* 文件类型标签 */}
  137. <Badge
  138. className={`
  139. absolute bottom-1 left-1 text-xs px-1 py-0
  140. ${getFileTypeBadge(file.type).color}
  141. `}
  142. >
  143. {getFileTypeBadge(file.type).text}
  144. </Badge>
  145. </div>
  146. );
  147. };
  148. interface FilePreviewProps {
  149. fileIds?: number[];
  150. files?: any[];
  151. maxCount?: number;
  152. size?: 'small' | 'medium' | 'large';
  153. showCount?: boolean;
  154. onFileClick?: (file: FileItem) => void;
  155. className?: string;
  156. }
  157. const FilePreview: React.FC<FilePreviewProps> = ({
  158. fileIds = [],
  159. files = [],
  160. maxCount = 6,
  161. size = 'medium',
  162. showCount = true,
  163. onFileClick,
  164. className = '',
  165. }) => {
  166. // 合并文件ID和文件对象
  167. const allFileIds = [...fileIds, ...(files?.map(f => f.id) || [])];
  168. const uniqueFileIds = [...new Set(allFileIds)].filter(Boolean);
  169. // 使用 React Query 查询文件详情
  170. const { data: fileDetails, isLoading, error } = useQuery({
  171. queryKey: ['files', uniqueFileIds],
  172. queryFn: async () => {
  173. if (uniqueFileIds.length === 0) return [];
  174. const promises = uniqueFileIds.map(async (id) => {
  175. try {
  176. const response = await fileClient[':id']['$get']({ param: { id: id.toString() } });
  177. if (response.ok) {
  178. return response.json();
  179. }
  180. return null;
  181. } catch (error) {
  182. console.error(`获取文件 ${id} 详情失败:`, error);
  183. return null;
  184. }
  185. });
  186. const results = await Promise.all(promises);
  187. return results.filter(Boolean) as FileItem[];
  188. },
  189. enabled: uniqueFileIds.length > 0,
  190. staleTime: 5 * 60 * 1000, // 5分钟
  191. gcTime: 10 * 60 * 1000, // 10分钟
  192. });
  193. // 加载状态
  194. if (isLoading) {
  195. return (
  196. <div className={`flex justify-center py-8 ${className}`}>
  197. <div className="space-y-2">
  198. <div className="flex gap-2 justify-center">
  199. {[...Array(Math.min(maxCount, 3))].map((_, i) => (
  200. <Skeleton key={i} className={`rounded-lg ${size === 'small' ? 'w-12 h-12' : size === 'medium' ? 'w-20 h-20' : 'w-24 h-24'}`} />
  201. ))}
  202. </div>
  203. <p className="text-sm text-gray-500 text-center">加载中...</p>
  204. </div>
  205. </div>
  206. );
  207. }
  208. // 错误状态
  209. if (error) {
  210. return (
  211. <div className={`flex flex-col items-center justify-center py-8 ${className}`}>
  212. <FileText className="h-12 w-12 text-gray-400 mb-2" />
  213. <p className="text-sm text-gray-600">加载图片失败</p>
  214. <Button
  215. variant="outline"
  216. size="sm"
  217. className="mt-2"
  218. onClick={() => {
  219. // 这里可以添加重试逻辑
  220. toast.info('请刷新页面重试');
  221. }}
  222. >
  223. 重试
  224. </Button>
  225. </div>
  226. );
  227. }
  228. const displayFiles = fileDetails?.slice(0, maxCount) || [];
  229. const remainingCount = Math.max(0, (fileDetails?.length || 0) - maxCount);
  230. // 空状态
  231. if (displayFiles.length === 0) {
  232. return (
  233. <div className={`flex flex-col items-center justify-center py-6 ${className}`}>
  234. <FileText className="h-12 w-12 text-gray-400 mb-2" />
  235. <p className="text-sm text-gray-600">暂无图片</p>
  236. </div>
  237. );
  238. }
  239. return (
  240. <div className={className}>
  241. <div className="flex flex-wrap gap-2 items-start">
  242. {displayFiles.map((file, index) => (
  243. <FilePreviewItem
  244. key={file.id}
  245. file={file}
  246. size={size}
  247. index={index}
  248. total={displayFiles.length}
  249. onClick={onFileClick}
  250. />
  251. ))}
  252. </div>
  253. {/* 剩余数量提示 */}
  254. {showCount && remainingCount > 0 && (
  255. <div className="mt-2 text-sm text-gray-500">
  256. 还有 {remainingCount} 个文件未显示
  257. </div>
  258. )}
  259. </div>
  260. );
  261. };
  262. // 导出组件和类型
  263. export default FilePreview;
  264. export type { FilePreviewProps };