ImageSelector.tsx 12 KB

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