"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { formatBytes } from "@suphark/ui/lib/formatters"; import { cn } from "@suphark/ui/lib/utils"; import { UploadCloud } from "lucide-react"; import { type ChangeEvent, type DragEvent, type ReactNode, useCallback, useEffect, useId, useRef, useState, } from "react"; export type DropzoneRejectReason = "size" | "type" | "multiple"; export interface DropzoneText { /** ข้อความหลักในการ์ด */ title: string; /** "หรือ" ก่อนปุ่ม */ or: string; /** ปุ่มเลือกไฟล์ */ browse: string; /** ข้อความบน overlay ตอนลากไฟล์เข้าหน้า */ overlay: string; /** ขนาดสูงสุด — รับข้อความขนาดที่ฟอร์แมตแล้ว */ maxSize: (size: string) => string; } const TEXT: Record<"th" | "en", DropzoneText> = { th: { title: "ลากไฟล์มาวางที่นี่", or: "หรือ", browse: "เลือกไฟล์", overlay: "วางไฟล์ที่นี่", maxSize: (s) => `ไฟล์ละไม่เกิน ${s}`, }, en: { title: "Drag files here", or: "or", browse: "Browse files", overlay: "Drop files here", maxSize: (s) => `Up to ${s} per file`, }, }; export interface DropzoneProps { onFiles: (files: File[]) => void; /** ไฟล์ที่ไม่ผ่าน (เกินขนาด / ชนิดไม่ตรง accept / เกิน 1 ไฟล์เมื่อ multiple=false) */ onRejected?: (files: File[], reason: DropzoneRejectReason) => void; /** รับหลายไฟล์ (ค่าเริ่มต้น true) */ multiple?: boolean; /** เหมือน ``: "image/*,.pdf,application/zip" — ใช้กรองทั้งตอนเลือกและตอนวาง */ accept?: string; /** ขนาดสูงสุดต่อไฟล์ (byte) */ maxBytes?: number; disabled?: boolean; /** เลือกทั้งโฟลเดอร์ (`webkitdirectory`) — ตอนวางโฟลเดอร์จะไล่อ่านไฟล์ข้างในให้ */ directory?: boolean; /** ข้อความช่วยใต้ปุ่ม (ค่าเริ่มต้นแสดง maxBytes ถ้ามี) */ hint?: ReactNode; /** ไอคอนในการ์ด (ค่าเริ่มต้น UploadCloud) */ icon?: ReactNode; /** * โหมด overlay: ห่อ `children` (เช่น ตารางไฟล์) แล้วโชว์ชั้น "วางไฟล์ที่นี่" ทับเฉพาะตอนลากไฟล์เข้าหน้า * ไม่ส่ง children = การ์ดเดี่ยว (เส้นประ + ไอคอน + ข้อความ + ปุ่มเลือกไฟล์) */ overlay?: boolean; children?: ReactNode; language?: "th" | "en"; text?: Partial; className?: string; } /** ตรวจตาม `accept` ของ input: ".pdf" (นามสกุล), "image/*" (กลุ่ม), "application/pdf" (ตรงตัว) */ export function matchesAccept(file: File, accept?: string): boolean { if (!accept?.trim()) return true; const name = file.name.toLowerCase(); const type = file.type.toLowerCase(); return accept .split(",") .map((a) => a.trim().toLowerCase()) .filter(Boolean) .some((a) => { if (a.startsWith(".")) return name.endsWith(a); if (a.endsWith("/*")) return type.startsWith(a.slice(0, -1)); return type === a; }); } function hasFiles(e: DragEvent | globalThis.DragEvent): boolean { return Array.from(e.dataTransfer?.types ?? []).includes("Files"); } /** ไล่อ่านไฟล์จาก DataTransfer — รองรับโฟลเดอร์ผ่าน webkitGetAsEntry (Chrome/Edge/Safari) */ async function readDataTransfer(dt: DataTransfer, recurse: boolean): Promise { const items = Array.from(dt.items ?? []); const entries = recurse ? items.map((it) => (it.kind === "file" ? it.webkitGetAsEntry?.() : null)) : []; if (!recurse || entries.every((e) => !e)) return Array.from(dt.files ?? []); const out: File[] = []; async function walk(entry: FileSystemEntry | null): Promise { if (!entry) return; if (entry.isFile) { const file = await new Promise((resolve) => (entry as FileSystemFileEntry).file(resolve, () => resolve(null)), ); if (file) out.push(file); } else if (entry.isDirectory) { const reader = (entry as FileSystemDirectoryEntry).createReader(); // readEntries คืนเป็นชุด (Chrome สูงสุด 100/ครั้ง) ต้องเรียกซ้ำจนว่าง for (;;) { const batch = await new Promise((resolve) => reader.readEntries(resolve, () => resolve([])), ); if (batch.length === 0) break; for (const child of batch) await walk(child); } } } for (const entry of entries) await walk(entry); return out; } /** * พื้นที่ลากวางไฟล์ 2 โหมด — การ์ดเดี่ยว หรือ overlay ห่อเนื้อหา (แบบ Google Drive): * กรอง `accept`/`maxBytes`/`multiple` ให้แล้วส่ง `onFiles` เฉพาะที่ผ่าน ที่ไม่ผ่านไป `onRejected` แยกตามเหตุผล * คลิกการ์ด/ปุ่ม/Enter เปิด file picker (input ซ่อน); `directory` เลือกและวางทั้งโฟลเดอร์ */ export function Dropzone({ onFiles, onRejected, multiple = true, accept, maxBytes, disabled = false, directory = false, hint, icon, overlay = false, children, language = "th", text: textProp, className, }: DropzoneProps) { const text: DropzoneText = { ...TEXT[language], ...textProp }; const inputRef = useRef(null); const inputId = useId(); const [active, setActive] = useState(false); // dragenter/dragleave ยิงซ้ำตามลูกทุกตัว — นับลึกเพื่อรู้ว่าออกนอกจริง const depth = useRef(0); const submit = useCallback( (all: File[]) => { const bySize: File[] = []; const byType: File[] = []; let ok = all.filter((f) => { if (!matchesAccept(f, accept)) { byType.push(f); return false; } if (maxBytes != null && f.size > maxBytes) { bySize.push(f); return false; } return true; }); if (!multiple && ok.length > 1) { onRejected?.(ok.slice(1), "multiple"); ok = ok.slice(0, 1); } if (byType.length) onRejected?.(byType, "type"); if (bySize.length) onRejected?.(bySize, "size"); if (ok.length) onFiles(ok); }, [accept, maxBytes, multiple, onFiles, onRejected], ); function openPicker() { if (!disabled) inputRef.current?.click(); } function onInputChange(e: ChangeEvent) { const files = Array.from(e.target.files ?? []); e.target.value = ""; // เลือกไฟล์เดิมซ้ำได้ if (files.length) submit(files); } // โหมด overlay: รู้ว่ากำลังลากไฟล์เข้าหน้า (window) — ไม่ต้องลากให้ถึงตัว wrapper ก่อน useEffect(() => { if (!overlay || disabled) return; const enter = (e: globalThis.DragEvent) => { if (!hasFiles(e)) return; depth.current += 1; setActive(true); }; const leave = () => { depth.current = Math.max(0, depth.current - 1); if (depth.current === 0) setActive(false); }; const over = (e: globalThis.DragEvent) => { if (hasFiles(e)) e.preventDefault(); // ไม่งั้น browser เปิดไฟล์เมื่อวางนอก dropzone }; const drop = (e: globalThis.DragEvent) => { // วางนอกกรอบ: dragover อย่างเดียวไม่พอ ต้องกัน drop ด้วย ไม่งั้นเบราว์เซอร์เปิดไฟล์แทนหน้านี้ if (hasFiles(e)) e.preventDefault(); depth.current = 0; setActive(false); }; window.addEventListener("dragenter", enter); window.addEventListener("dragleave", leave); window.addEventListener("dragover", over); window.addEventListener("drop", drop); return () => { window.removeEventListener("dragenter", enter); window.removeEventListener("dragleave", leave); window.removeEventListener("dragover", over); window.removeEventListener("drop", drop); }; }, [overlay, disabled]); const dragProps = { onDragEnter: (e: DragEvent) => { if (disabled || !hasFiles(e)) return; e.preventDefault(); if (!overlay) { depth.current += 1; setActive(true); } }, onDragOver: (e: DragEvent) => { if (disabled || !hasFiles(e)) return; e.preventDefault(); e.dataTransfer.dropEffect = "copy"; }, onDragLeave: () => { if (overlay) return; depth.current = Math.max(0, depth.current - 1); if (depth.current === 0) setActive(false); }, onDrop: async (e: DragEvent) => { if (disabled || !hasFiles(e)) return; e.preventDefault(); depth.current = 0; setActive(false); const files = await readDataTransfer(e.dataTransfer, directory); if (files.length) submit(files); }, }; const input = ( e.stopPropagation()} // React ไม่รู้จัก prop นี้ — ส่งเป็น attribute ตรง ๆ {...(directory ? { webkitdirectory: "" } : {})} /> ); if (overlay) { return (
{children} {input} {active && (
{icon ??
)}
); } const defaultHint = hint ?? (maxBytes != null ? text.maxSize(formatBytes(maxBytes, "en-US")) : null); return (
{icon ??

{text.title}

{text.or}

{defaultHint &&

{defaultHint}

} {input}
); }