| 2 | import { useEffect, useState } from 'react' |
| 3 | |
| 4 | export default function FileUpload({ |
| 5 | onDropFile, |
| 6 | onClick |
| 7 | }: { |
| 8 | onDropFile: (file?: File) => void |
| 9 | onClick: () => void |
| 10 | }) { |
| 11 | const [dragging, setDragging] = useState(false) |
| 12 | |
| 13 | useEffect(() => { |
| 14 | const handlePaste = (e: ClipboardEvent) => { |
| 15 | const items = e.clipboardData?.items |
| 16 | let file: File | null | undefined |
| 17 | if (items) { |
| 18 | for (const item of items) { |
| 19 | if (item.type.startsWith('image/')) { |
| 20 | file = item.getAsFile() |
| 21 | break |
| 22 | } |
| 23 | } |
| 24 | if (file) { |
| 25 | console.log('Pasted file type', file.type) |
| 26 | onDropFile(file) |
| 27 | } else { |
| 28 | console.error('File type not supported', items[0].type) |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | window.addEventListener('paste', handlePaste) |
| 34 | return () => { |
| 35 | window.removeEventListener('paste', handlePaste) |
| 36 | } |
| 37 | }, [onDropFile]) |
| 38 | |
| 39 | return ( |
| 40 | <div |
| 41 | className='flex h-full items-center bg-background' |
| 42 | onKeyUp={e => { |
| 43 | if (e.key === 'Enter') { |
| 44 | onClick() |
| 45 | } |
| 46 | }} |
| 47 | role='button' |
| 48 | tabIndex={0} |
| 49 | onClick={onClick} |
| 50 | onDragEnter={() => setDragging(true)} |
| 51 | onDragExit={() => setDragging(false)} |
| 52 | onDrop={(e: React.DragEvent) => { |
| 53 | e.preventDefault() |
| 54 | setDragging(false) |
| 55 | |
| 56 | let file: File | null | undefined |
| 57 | if (e.dataTransfer.items.length > 0) { |
| 58 | for (const item of e.dataTransfer.items) { |
| 59 | if (item.kind === 'file') { |
| 60 | file = item.getAsFile() |
| 61 | if (file?.type.startsWith('image/')) break |