image-input.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import { useState, useRef, useEffect, useCallback } from 'react';
  2. import { Tabs, TabsContent, TabsList, TabsTrigger } from './tabs';
  3. import { Button } from './button';
  4. import { Input } from './input';
  5. import { Label } from './label';
  6. import { Alert, AlertDescription } from './alert';
  7. import {
  8. Upload,
  9. Link as LinkIcon,
  10. X,
  11. Loader2,
  12. CheckCircle,
  13. AlertCircle,
  14. } from 'lucide-react';
  15. import {
  16. validateImageInput,
  17. validateImageUrlWithBase64,
  18. getImageDisplayName,
  19. fileToDataURL,
  20. type ImageValidationResult
  21. } from '../../lib/image-validation';
  22. export interface ImageInputProps {
  23. value?: File | string | null;
  24. onChange: (file: File | string | null) => void;
  25. onValidation?: (result: ImageValidationResult) => void;
  26. disabled?: boolean;
  27. className?: string;
  28. maxSize?: number; // in bytes, default 10MB
  29. accept?: string; // file accept attribute
  30. placeholder?: string;
  31. showPreview?: boolean;
  32. previewClassName?: string;
  33. }
  34. export interface ImageInputState {
  35. mode: 'file' | 'url';
  36. validation: ImageValidationResult | null;
  37. isValidating: boolean;
  38. error: string | null;
  39. previewUrl: string | null;
  40. }
  41. export function ImageInput({
  42. value,
  43. onChange,
  44. onValidation,
  45. disabled = false,
  46. className = '',
  47. maxSize = 10 * 1024 * 1024, // 10MB
  48. accept = 'image/*',
  49. placeholder = 'Enter image URL or select a file',
  50. showPreview = true,
  51. previewClassName = ''
  52. }: ImageInputProps) {
  53. const [state, setState] = useState<ImageInputState>({
  54. mode: 'file',
  55. validation: null,
  56. isValidating: false,
  57. error: null,
  58. previewUrl: null
  59. });
  60. const [urlInput, setUrlInput] = useState('');
  61. const fileInputRef = useRef<HTMLInputElement>(null);
  62. const validationTimeoutRef = useRef<NodeJS.Timeout | null>(null);
  63. const handleFileValidation = useCallback(async (file: File) => {
  64. setState(prev => ({ ...prev, isValidating: true, error: null }));
  65. const result = await validateImageInput(file);
  66. let previewUrl: string | null = null;
  67. if (result.isValid) {
  68. try {
  69. previewUrl = await fileToDataURL(file);
  70. } catch (error) {
  71. console.error('Failed to create preview URL:', error);
  72. }
  73. }
  74. setState(prev => ({
  75. ...prev,
  76. isValidating: false,
  77. validation: result,
  78. error: result.isValid ? null : (result.error || null),
  79. previewUrl
  80. }));
  81. onValidation?.(result);
  82. }, [onValidation]);
  83. const handleUrlValidation = useCallback(async (url: string | null) => {
  84. if (!url || !url.trim()) {
  85. setState(prev => ({
  86. ...prev,
  87. validation: null,
  88. error: null,
  89. previewUrl: null
  90. }));
  91. onValidation?.({ isValid: false, error: 'Please enter a URL' });
  92. return;
  93. }
  94. setState(prev => ({ ...prev, isValidating: true, error: null }));
  95. try {
  96. const result = await validateImageUrlWithBase64(url);
  97. // Use temporary URL for preview if available, otherwise fall back to base64 data or original URL
  98. const previewUrl = result.isValid ? (result.tempUrl || result.base64Data || url) : null;
  99. setState(prev => ({
  100. ...prev,
  101. isValidating: false,
  102. validation: result,
  103. error: result.isValid ? null : (result.error || null),
  104. previewUrl
  105. }));
  106. onValidation?.(result);
  107. } catch (error) {
  108. const errorMessage = error instanceof Error ? error.message : 'Failed to validate URL';
  109. setState(prev => ({
  110. ...prev,
  111. isValidating: false,
  112. validation: { isValid: false, error: errorMessage },
  113. error: errorMessage,
  114. previewUrl: null
  115. }));
  116. onValidation?.({ isValid: false, error: errorMessage });
  117. }
  118. }, [onValidation]);
  119. // Handle external value changes
  120. useEffect(() => {
  121. if (value === null) {
  122. setState(prev => ({
  123. ...prev,
  124. validation: null,
  125. error: null,
  126. previewUrl: null
  127. }));
  128. setUrlInput('');
  129. return;
  130. }
  131. if (value instanceof File) {
  132. // File mode
  133. setState(prev => ({
  134. ...prev,
  135. mode: 'file',
  136. validation: null,
  137. error: null,
  138. previewUrl: null
  139. }));
  140. setUrlInput('');
  141. // Validate file immediately
  142. handleFileValidation(value);
  143. } else {
  144. // URL mode - value is a string (not File, not null)
  145. // Don't set preview URL yet, wait for validation to complete
  146. setState(prev => ({
  147. ...prev,
  148. mode: 'url',
  149. validation: null,
  150. error: null,
  151. previewUrl: null
  152. }));
  153. // value should be a string here, but cast it to be safe
  154. setUrlInput(value || '');
  155. // Validate URL (with debounce)
  156. if (validationTimeoutRef.current) {
  157. clearTimeout(validationTimeoutRef.current);
  158. }
  159. validationTimeoutRef.current = setTimeout(() => {
  160. // Only validate if we have a non-empty string
  161. const urlValue = typeof value === 'string' ? value : null;
  162. if (urlValue && urlValue.trim()) {
  163. handleUrlValidation(urlValue);
  164. } else {
  165. handleUrlValidation(null);
  166. }
  167. }, 500);
  168. }
  169. }, [value, maxSize, handleFileValidation, handleUrlValidation]);
  170. // Cleanup timeout on unmount
  171. useEffect(() => {
  172. return () => {
  173. if (validationTimeoutRef.current) {
  174. clearTimeout(validationTimeoutRef.current);
  175. }
  176. };
  177. }, []);
  178. const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
  179. const file = event.target.files?.[0];
  180. if (file) {
  181. onChange(file);
  182. }
  183. };
  184. const handleUrlInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {
  185. const url = event.target.value;
  186. setUrlInput(url);
  187. onChange(url || null);
  188. };
  189. const handleModeChange = (mode: 'file' | 'url') => {
  190. setState(prev => ({
  191. ...prev,
  192. mode,
  193. validation: null,
  194. error: null,
  195. previewUrl: null
  196. }));
  197. onChange(null);
  198. setUrlInput('');
  199. };
  200. const handleClear = () => {
  201. onChange(null);
  202. setUrlInput('');
  203. setState(prev => ({
  204. ...prev,
  205. validation: null,
  206. error: null,
  207. previewUrl: null
  208. }));
  209. };
  210. const isValid = state.validation?.isValid;
  211. const hasError = state.error && !isValid;
  212. const canPreview = isValid && state.previewUrl;
  213. const isCorsBlocked = state.validation?.isCorsBlocked;
  214. const hasBase64Data = !!state.validation?.base64Data;
  215. return (
  216. <div className={`image-input ${className}`}>
  217. <Tabs value={state.mode} onValueChange={(value: string) => handleModeChange(value as 'file' | 'url')}>
  218. <TabsList className="grid w-full grid-cols-2">
  219. <TabsTrigger value="file" disabled={disabled}>
  220. <Upload className="w-4 h-4 mr-2" />
  221. Upload File
  222. </TabsTrigger>
  223. <TabsTrigger value="url" disabled={disabled}>
  224. <LinkIcon className="w-4 h-4 mr-2" />
  225. From URL
  226. </TabsTrigger>
  227. </TabsList>
  228. <TabsContent value="file" className="space-y-4">
  229. <div className="space-y-2">
  230. <Label htmlFor="file-upload">Choose Image File</Label>
  231. <div className="flex gap-2">
  232. <Input
  233. ref={fileInputRef}
  234. id="file-upload"
  235. type="file"
  236. accept={accept}
  237. onChange={handleFileSelect}
  238. disabled={disabled}
  239. className="flex-1"
  240. />
  241. {value instanceof File && (
  242. <Button
  243. type="button"
  244. variant="outline"
  245. onClick={() => fileInputRef.current?.click()}
  246. disabled={disabled}
  247. >
  248. Browse
  249. </Button>
  250. )}
  251. </div>
  252. {typeof value === 'string' && value && (
  253. <p className="text-sm text-gray-500">
  254. Current: {getImageDisplayName(value)}
  255. </p>
  256. )}
  257. </div>
  258. </TabsContent>
  259. <TabsContent value="url" className="space-y-4">
  260. <div className="space-y-2">
  261. <Label htmlFor="url-input">Image URL</Label>
  262. <Input
  263. id="url-input"
  264. type="url"
  265. value={urlInput}
  266. onChange={handleUrlInputChange}
  267. placeholder={placeholder}
  268. disabled={disabled}
  269. className="flex-1"
  270. />
  271. <p className="text-xs text-gray-500">
  272. Enter a URL that ends with an image extension (.jpg, .png, .gif, etc.)
  273. </p>
  274. </div>
  275. </TabsContent>
  276. </Tabs>
  277. {/* Validation Status */}
  278. {state.isValidating && (
  279. <div className="flex items-center gap-2 text-sm text-gray-500">
  280. <Loader2 className="w-4 h-4 animate-spin" />
  281. Validating and downloading image...
  282. </div>
  283. )}
  284. {isValid && (
  285. <Alert className="mt-4">
  286. <CheckCircle className="h-4 w-4" />
  287. <AlertDescription>
  288. Image is valid and ready to use
  289. {state.validation?.filename && ` (${state.validation.filename})`}
  290. {hasBase64Data && (
  291. <span className="block mt-1 text-xs text-green-600">
  292. ✓ Image downloaded and cached for preview
  293. </span>
  294. )}
  295. {isCorsBlocked && (
  296. <span className="block mt-1 text-xs text-yellow-600">
  297. Note: Downloaded using fallback method due to CORS restrictions
  298. </span>
  299. )}
  300. </AlertDescription>
  301. </Alert>
  302. )}
  303. {hasError && (
  304. <Alert variant="destructive" className="mt-4">
  305. <AlertCircle className="h-4 w-4" />
  306. <AlertDescription>
  307. {state.error}
  308. {state.error?.includes('CORS') && (
  309. <span className="block mt-1 text-xs">
  310. Try using a different image URL or upload the file directly
  311. </span>
  312. )}
  313. </AlertDescription>
  314. </Alert>
  315. )}
  316. {/* Image Preview */}
  317. {showPreview && canPreview && (
  318. <div className={`mt-4 ${previewClassName}`}>
  319. <Label>Preview</Label>
  320. <div className="mt-2 border rounded-lg p-4 bg-gray-50">
  321. <div className="flex items-center justify-center h-48 bg-white rounded border">
  322. <img
  323. src={state.previewUrl || ''}
  324. alt="Image preview"
  325. className="max-w-full max-h-full object-contain"
  326. />
  327. </div>
  328. </div>
  329. </div>
  330. )}
  331. {/* Clear Button */}
  332. {value && (
  333. <div className="mt-4 flex justify-end">
  334. <Button
  335. type="button"
  336. variant="outline"
  337. onClick={handleClear}
  338. disabled={disabled}
  339. className="text-red-600 hover:text-red-700"
  340. >
  341. <X className="w-4 h-4 mr-2" />
  342. Clear Selection
  343. </Button>
  344. </div>
  345. )}
  346. </div>
  347. );
  348. }
  349. export default ImageInput;