ImageSelector.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import React, { useState, useEffect, useRef } 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, 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. interface ImageSelectorProps {
  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. selectedFiles?: number[];
  28. onMultipleSelect?: (fileIds: number[]) => void;
  29. }
  30. export const ImageSelector: React.FC<ImageSelectorProps> = ({
  31. value,
  32. onChange,
  33. accept = 'image/*',
  34. maxSize = 5,
  35. uploadPath = '/images',
  36. uploadButtonText = '上传图片',
  37. previewSize = 'medium',
  38. showPreview = true,
  39. placeholder = '选择图片',
  40. title = '选择图片',
  41. description = '上传新图片或从已有图片中选择',
  42. filterType = 'image',
  43. allowMultiple = false,
  44. selectedFiles = [],
  45. onMultipleSelect,
  46. }) => {
  47. const [isOpen, setIsOpen] = useState(false);
  48. const [selectedFile, setSelectedFile] = useState<FileType | null>(null);
  49. const [localSelectedFiles, setLocalSelectedFiles] = useState<number[]>(selectedFiles);
  50. const prevSelectedFilesRef = useRef(selectedFiles);
  51. // 获取当前选中的文件详情
  52. const { data: currentFile } = useQuery({
  53. queryKey: ['file-detail', value],
  54. queryFn: async () => {
  55. if (!value) return null;
  56. const response = await fileClient[':id']['$get']({ param: { id: value.toString() } });
  57. if (response.status !== 200) throw new Error('获取文件详情失败');
  58. return response.json();
  59. },
  60. enabled: !!value,
  61. });
  62. // 当对话框打开时,设置当前选中的图片
  63. useEffect(() => {
  64. if (isOpen) {
  65. if (allowMultiple) {
  66. setLocalSelectedFiles(selectedFiles);
  67. } else if (value && currentFile) {
  68. setSelectedFile(currentFile);
  69. }
  70. }
  71. }, [isOpen, value, currentFile, allowMultiple]);
  72. // 修复无限循环问题:使用ref比较数组内容
  73. useEffect(() => {
  74. const areArraysEqual = (a: number[], b: number[]) => {
  75. if (a.length !== b.length) return false;
  76. const sortedA = [...a].sort();
  77. const sortedB = [...b].sort();
  78. return sortedA.every((val, index) => val === sortedB[index]);
  79. };
  80. if (!areArraysEqual(prevSelectedFilesRef.current, selectedFiles)) {
  81. setLocalSelectedFiles(selectedFiles);
  82. prevSelectedFilesRef.current = selectedFiles;
  83. }
  84. }, [selectedFiles]);
  85. // 获取图片列表
  86. const { data: filesData, isLoading, refetch } = useQuery({
  87. queryKey: ['images-for-selection', filterType] as const,
  88. queryFn: async () => {
  89. const response = await fileClient.$get({
  90. query: {
  91. page: 1,
  92. pageSize: 50,
  93. ...(filterType !== 'all' && { keyword: filterType })
  94. }
  95. });
  96. if (response.status !== 200) throw new Error('获取图片列表失败');
  97. return response.json();
  98. },
  99. enabled: isOpen,
  100. });
  101. const images = filesData?.data?.filter((f: any) => {
  102. if (filterType === 'all') return true;
  103. if (filterType === 'image') return f?.type?.startsWith('image/');
  104. return f?.type?.includes(filterType);
  105. }) || [];
  106. const handleSelectImage = (file: FileType) => {
  107. if (allowMultiple) {
  108. setLocalSelectedFiles(prev => {
  109. const newSelection = prev.includes(file.id)
  110. ? prev.filter(id => id !== file.id)
  111. : [...prev, file.id];
  112. return newSelection;
  113. });
  114. } else {
  115. setSelectedFile(prevSelected => {
  116. if (prevSelected?.id === file.id) {
  117. return null;
  118. }
  119. return file;
  120. });
  121. }
  122. };
  123. const handleConfirm = () => {
  124. if (allowMultiple) {
  125. if (onMultipleSelect) {
  126. onMultipleSelect(localSelectedFiles);
  127. } else if (onChange) {
  128. onChange(localSelectedFiles);
  129. }
  130. setIsOpen(false);
  131. return;
  132. }
  133. if (!selectedFile) {
  134. toast.warning('请选择一个图片');
  135. return;
  136. }
  137. if (onChange) {
  138. onChange(selectedFile.id);
  139. }
  140. setIsOpen(false);
  141. setSelectedFile(null);
  142. };
  143. const handleCancel = () => {
  144. setIsOpen(false);
  145. setSelectedFile(null);
  146. setLocalSelectedFiles(selectedFiles);
  147. };
  148. const handleUploadSuccess = () => {
  149. toast.success('图片上传成功!请从列表中选择新上传的图片');
  150. refetch();
  151. };
  152. const getPreviewSize = () => {
  153. switch (previewSize) {
  154. case 'small':
  155. return 'h-16 w-16';
  156. case 'medium':
  157. return 'h-24 w-24';
  158. case 'large':
  159. return 'h-32 w-32';
  160. default:
  161. return 'h-24 w-24';
  162. }
  163. };
  164. const handleRemoveImage = (e: React.MouseEvent) => {
  165. e.stopPropagation();
  166. onChange?.(null);
  167. };
  168. const isSelected = (fileId: number) => {
  169. if (allowMultiple) {
  170. return localSelectedFiles.includes(fileId);
  171. }
  172. return selectedFile?.id === fileId;
  173. };
  174. return (
  175. <>
  176. <div className="space-y-4">
  177. {showPreview && (
  178. <div className="flex items-center space-x-4">
  179. <div className="relative group">
  180. <div
  181. className={cn(
  182. getPreviewSize(),
  183. "border-2 border-dashed cursor-pointer hover:border-primary transition-colors rounded-lg overflow-hidden flex items-center justify-center bg-gray-100"
  184. )}
  185. onClick={() => setIsOpen(true)}
  186. >
  187. {currentFile ? (
  188. <img
  189. src={currentFile.fullUrl}
  190. alt={currentFile.name}
  191. className="w-full h-full object-cover"
  192. />
  193. ) : (
  194. <div className="flex flex-col items-center justify-center text-gray-400">
  195. <ImageIcon className="h-8 w-8 mb-1" />
  196. <span className="text-xs">{placeholder}</span>
  197. </div>
  198. )}
  199. </div>
  200. {currentFile && (
  201. <button
  202. type="button"
  203. className="absolute -top-2 -right-2 bg-red-500 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
  204. onClick={handleRemoveImage}
  205. >
  206. <X className="h-3 w-3" />
  207. </button>
  208. )}
  209. </div>
  210. <div className="space-y-2">
  211. <Button
  212. type="button"
  213. variant="outline"
  214. onClick={() => setIsOpen(true)}
  215. className="text-sm"
  216. >
  217. {currentFile ? '更换图片' : placeholder}
  218. </Button>
  219. {currentFile && (
  220. <p className="text-xs text-muted-foreground truncate w-40 sm:w-64">
  221. 当前: {currentFile.name}
  222. </p>
  223. )}
  224. </div>
  225. </div>
  226. )}
  227. {!showPreview && (
  228. <Button
  229. type="button"
  230. variant="outline"
  231. onClick={() => setIsOpen(true)}
  232. className="w-full"
  233. >
  234. {currentFile ? '更换图片' : placeholder}
  235. </Button>
  236. )}
  237. </div>
  238. <Dialog open={isOpen} onOpenChange={setIsOpen}>
  239. <DialogContent className="max-w-4xl max-h-[90vh]">
  240. <DialogHeader>
  241. <DialogTitle>{title}</DialogTitle>
  242. <DialogDescription>
  243. {description}
  244. </DialogDescription>
  245. </DialogHeader>
  246. <div className="space-y-4">
  247. {/* 图片列表 */}
  248. <div className="space-y-2 max-h-96 overflow-y-auto p-1">
  249. {isLoading ? (
  250. <Card>
  251. <CardContent className="text-center py-8">
  252. <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
  253. <p className="text-gray-500 mt-2">加载中...</p>
  254. </CardContent>
  255. </Card>
  256. ) : (
  257. <div className="grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-3">
  258. {/* 上传区域 - 作为第一项 */}
  259. <div className="relative cursor-pointer transition-all duration-200">
  260. <div className="rounded-lg border-2 border-dashed border-gray-300 hover:border-primary transition-colors hover:scale-105">
  261. <div className="p-2 h-24 flex items-center justify-center">
  262. <MinioUploader
  263. uploadPath={uploadPath}
  264. accept={accept}
  265. maxSize={maxSize}
  266. onUploadSuccess={handleUploadSuccess}
  267. buttonText="上传"
  268. size="minimal"
  269. displayMode="card"
  270. showUploadList={false}
  271. />
  272. </div>
  273. </div>
  274. <p className="text-xs text-center mt-1 text-muted-foreground">
  275. 上传新图片
  276. </p>
  277. </div>
  278. {/* 现有图片列表 */}
  279. {images.map((file) => (
  280. <div
  281. key={file.id}
  282. className={cn(
  283. "relative cursor-pointer transition-all duration-200",
  284. "hover:scale-105"
  285. )}
  286. onClick={() => handleSelectImage(file)}
  287. >
  288. <div
  289. className={cn(
  290. "relative rounded-lg overflow-hidden border-2 aspect-square",
  291. isSelected(file.id)
  292. ? "border-primary ring-2 ring-primary ring-offset-2"
  293. : "border-gray-200 hover:border-primary"
  294. )}
  295. >
  296. <img
  297. src={file.fullUrl}
  298. alt={file.name}
  299. className="w-full h-full object-cover"
  300. />
  301. {isSelected(file.id) && (
  302. <div className="absolute inset-0 bg-primary/20 flex items-center justify-center">
  303. <Check className="h-6 w-6 text-white bg-primary rounded-full p-1" />
  304. </div>
  305. )}
  306. <div className="absolute top-1 right-1">
  307. <Eye
  308. className="h-4 w-4 text-white bg-black/50 rounded-full p-0.5 cursor-pointer hover:bg-black/70"
  309. onClick={(e) => {
  310. e.stopPropagation();
  311. window.open(file.fullUrl, '_blank');
  312. }}
  313. />
  314. </div>
  315. </div>
  316. <p className="text-xs text-center mt-1 truncate">
  317. {file.name}
  318. </p>
  319. </div>
  320. ))}
  321. {/* 空状态 - 当没有图片时显示 */}
  322. {images.length === 0 && (
  323. <div className="col-span-full">
  324. <Card>
  325. <CardContent className="text-center py-8">
  326. <div className="flex flex-col items-center">
  327. <Upload className="h-12 w-12 text-gray-400 mb-4" />
  328. <p className="text-gray-600">暂无图片</p>
  329. <p className="text-sm text-gray-500 mt-2">请上传图片文件</p>
  330. </div>
  331. </CardContent>
  332. </Card>
  333. </div>
  334. )}
  335. </div>
  336. )}
  337. </div>
  338. </div>
  339. <DialogFooter>
  340. <Button type="button" variant="outline" onClick={handleCancel}>
  341. 取消
  342. </Button>
  343. <Button
  344. type="button"
  345. onClick={handleConfirm}
  346. disabled={allowMultiple ? localSelectedFiles.length === 0 : !selectedFile}
  347. >
  348. {allowMultiple ? `确认选择 (${localSelectedFiles.length})` : '确认选择'}
  349. </Button>
  350. </DialogFooter>
  351. </DialogContent>
  352. </Dialog>
  353. </>
  354. );
  355. };
  356. export default ImageSelector;