|
| 1 | +import { FormControl, FormField, FormMessage, Root } from '@radix-ui/react-form' |
| 2 | +import { PlusIcon } from 'lucide-react' |
| 3 | +import { useRef, useState } from 'react' |
| 4 | +import { MAX_FILE_SIZE } from '@/constants/files.ts' |
| 5 | +import { formatFileSize } from '@/utils/format-file-size.ts' |
| 6 | +import { ButtonBase as Button } from '../ui/button/button-base.tsx' |
| 7 | + |
| 8 | +interface UploadButtonProps { |
| 9 | + onUpload: (file: File) => void |
| 10 | + isUploading?: boolean |
| 11 | + accept?: string[] |
| 12 | + maxSize?: number |
| 13 | +} |
| 14 | + |
| 15 | +export function UploadButton({ |
| 16 | + onUpload, |
| 17 | + isUploading = false, |
| 18 | + accept = ['*'], |
| 19 | + maxSize = MAX_FILE_SIZE, |
| 20 | +}: UploadButtonProps) { |
| 21 | + const fileInputRef = useRef<HTMLInputElement>(null) |
| 22 | + const [error, setError] = useState<string | null>(null) |
| 23 | + |
| 24 | + function handleButtonClick() { |
| 25 | + fileInputRef.current?.click() |
| 26 | + } |
| 27 | + |
| 28 | + function handleFileChange(e: React.ChangeEvent<HTMLInputElement>) { |
| 29 | + const file = e.target.files?.[0] |
| 30 | + if (file) { |
| 31 | + if (file.size > maxSize) { |
| 32 | + setError(`File is too large. Maximum size is ${formatFileSize(maxSize)}.`) |
| 33 | + if (fileInputRef.current) fileInputRef.current.value = '' |
| 34 | + return |
| 35 | + } |
| 36 | + |
| 37 | + setError(null) |
| 38 | + onUpload(file) |
| 39 | + if (fileInputRef.current) fileInputRef.current.value = '' |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return ( |
| 44 | + <Root className="flex flex-col gap-2 items-end" onSubmit={(e) => e.preventDefault()}> |
| 45 | + <FormField name="file"> |
| 46 | + <FormControl asChild> |
| 47 | + <input |
| 48 | + accept={accept.join(',')} |
| 49 | + className="hidden" |
| 50 | + multiple={false} |
| 51 | + onChange={handleFileChange} |
| 52 | + ref={fileInputRef} |
| 53 | + type="file" |
| 54 | + /> |
| 55 | + </FormControl> |
| 56 | + </FormField> |
| 57 | + <div className="w-content"> |
| 58 | + <Button |
| 59 | + disabled={isUploading} |
| 60 | + loading={isUploading} |
| 61 | + onClick={handleButtonClick} |
| 62 | + type="button" |
| 63 | + variant="primary" |
| 64 | + > |
| 65 | + <div className="flex items-center gap-2"> |
| 66 | + <PlusIcon size={20} /> |
| 67 | + <span>Add file</span> |
| 68 | + </div> |
| 69 | + </Button> |
| 70 | + </div> |
| 71 | + <div className="h-3"> |
| 72 | + {error && ( |
| 73 | + <FormField name="file"> |
| 74 | + <FormMessage className="text-sm text-red-500 mt-1 break-words max-w-full">{error}</FormMessage> |
| 75 | + </FormField> |
| 76 | + )} |
| 77 | + </div> |
| 78 | + </Root> |
| 79 | + ) |
| 80 | +} |
0 commit comments