feat: add file drop zone
This commit is contained in:
parent
2f61f1545d
commit
71305f3202
66
app/components/ui/drop-zone.tsx
Normal file
66
app/components/ui/drop-zone.tsx
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
import { useRef, useState, type ReactNode } from 'react';
|
||||||
|
import { cva } from 'class-variance-authority';
|
||||||
|
import { cn } from '~/lib/utils';
|
||||||
|
|
||||||
|
const zoneVariants = cva(
|
||||||
|
'cursor-pointer rounded-control border border-dashed transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40',
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
layout: {
|
||||||
|
row: 'px-4 py-3',
|
||||||
|
stack: 'flex flex-col items-center gap-2 px-4 py-[22px] text-center',
|
||||||
|
},
|
||||||
|
state: {
|
||||||
|
empty: 'border-border-dashed bg-surface-sunken hover:border-primary',
|
||||||
|
filled: 'border-solid border-border-control bg-background',
|
||||||
|
dragging: 'border-primary bg-primary/5',
|
||||||
|
invalid: 'border-danger/60 bg-surface-sunken',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
interface DropZoneProps {
|
||||||
|
id?: string;
|
||||||
|
accept: string;
|
||||||
|
layout: 'row' | 'stack';
|
||||||
|
filled?: boolean;
|
||||||
|
invalid?: boolean;
|
||||||
|
onFile: (file: File) => void;
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Click-or-drag file target with a hidden file input
|
||||||
|
export function DropZone({ id, accept, layout, filled, invalid, onFile, children }: DropZoneProps) {
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [dragging, setDragging] = useState(false);
|
||||||
|
const state = dragging ? 'dragging' : invalid && !filled ? 'invalid' : filled ? 'filled' : 'empty';
|
||||||
|
|
||||||
|
const pick = (file: File | undefined) => {
|
||||||
|
if (file) onFile(file);
|
||||||
|
if (inputRef.current) inputRef.current.value = '';
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
role='button'
|
||||||
|
tabIndex={0}
|
||||||
|
onClick={() => inputRef.current?.click()}
|
||||||
|
onKeyDown={(e) => (e.key === 'Enter' || e.key === ' ') && inputRef.current?.click()}
|
||||||
|
onDragOver={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragging(true);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragging(false)}
|
||||||
|
onDrop={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragging(false);
|
||||||
|
pick(e.dataTransfer.files[0]);
|
||||||
|
}}
|
||||||
|
className={cn(zoneVariants({ layout, state }))}
|
||||||
|
>
|
||||||
|
<input ref={inputRef} id={id} type='file' accept={accept} className='hidden' onChange={(e) => pick(e.target.files?.[0])} />
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
Loading…
x
Reference in New Issue
Block a user