ImageSelector.tsx 13 KB

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