Files
vpinball/components/FileDropZone.tsx
T

63 lines
1.7 KiB
TypeScript
Raw Normal View History

"use client";
import { useState, type ChangeEvent, type DragEvent, type ReactNode } from "react";
export const VPX_FILE_INPUT_ID = "vpx-file-input";
export interface FileDropZoneProps {
onFile: (file: File) => void;
onError: (message: string) => void;
children: ReactNode;
className?: string;
}
function validate(file: File | undefined, onFile: (file: File) => void, onError: (m: string) => void) {
if (!file) return;
if (!file.name.toLowerCase().endsWith(".vpx")) {
onError(`"${file.name}" isn't a .vpx file.`);
return;
}
onFile(file);
}
export default function FileDropZone({ onFile, onError, children, className = "" }: FileDropZoneProps) {
const [isDragging, setIsDragging] = useState(false);
const handleDrop = (e: DragEvent<HTMLDivElement>) => {
e.preventDefault();
setIsDragging(false);
validate(e.dataTransfer.files[0], onFile, onError);
};
const handleInputChange = (e: ChangeEvent<HTMLInputElement>) => {
validate(e.target.files?.[0], onFile, onError);
e.target.value = "";
};
return (
<div
onDragOver={(e) => {
e.preventDefault();
setIsDragging(true);
}}
onDragLeave={() => setIsDragging(false)}
onDrop={handleDrop}
className={`relative ${className}`}
>
{children}
<input
id={VPX_FILE_INPUT_ID}
type="file"
accept=".vpx"
className="sr-only"
onChange={handleInputChange}
/>
{isDragging && (
<div className="pointer-events-none absolute inset-0 z-20 flex items-center justify-center rounded-lg bg-ink/85 font-display text-3xl tracking-wide text-arc ring-2 ring-arc">
DROP TO LOAD
</div>
)}
</div>
);
}