Files
web-alterflixhub/app/components/admin/PhotosEditor.tsx
T
Bkk1234 2c5918a614 feat(admin): อัปโหลดรูปโรงหนังจากเครื่อง (เดิมใส่ได้แค่ URL)
- POST /api/admin/uploads (multipart, ≤8MB, ตรวจ magic bytes JPEG/PNG/WebP/AVIF)
  เก็บ data/uploads/cinemas/ คืน /uploads/cinemas/<slug>-<random>-<ts>.<ext>
- GET /uploads/** เสิร์ฟไฟล์อัปโหลด (Nitro route, immutable cache, กัน path traversal)
- PhotosEditor: ปุ่มอัปโหลด + ลากไฟล์มาวาง + Ctrl+V วางจากคลิปบอร์ด, หลายไฟล์พร้อมกัน
- app/lib/upload.ts กติกากลาง + upload.spec.ts (13 tests)
- docs: api.md, admin-guide.md (วิธีอัปโหลด), DESIGN.md, README
2026-11-15 23:36:35 +07:00

231 lines
8.1 KiB
TypeScript

import { IconPhotoUp, IconPlus, IconTrash } from "@tabler/icons-react";
import { useRef, useState } from "react";
import { MAX_UPLOAD_BYTES } from "@/lib/upload";
/**
* แก้รายการรูปโรงหนัง (อาร์เรย์ `photos`)
*
* รองรับ 3 ทาง:
* 1) อัปโหลดไฟล์จากเครื่อง (ปุ่ม / ลากมาวาง / Ctrl+V) → เก็บที่ data/uploads/cinemas
* 2) วางลิงก์หรือพาธเอง (`/images/cinemas/x.webp` หรือ URL ภายนอก)
* 3) สลับลำดับด้วย ↑/↓ · รูปแรก = ภาพหลักของแกลเลอรี
*/
type Props = {
photos: string[];
onChange: (next: string[]) => void;
inputClass: string;
labelClass: string;
/** slug ของโรงที่กำลังแก้ — ใช้ตั้งชื่อไฟล์อัปโหลด */
cinemaSlug?: string;
};
const smallButtonClass =
"flex min-h-9 items-center gap-1 rounded-lg border border-[#303030] px-2 text-xs text-[#999] transition hover:border-[#A92626] hover:text-[#D47272] disabled:opacity-50";
const uploadButtonClass =
"flex min-h-10 w-fit items-center gap-2 rounded-lg border border-[#A92626]/60 bg-[#1B1B1B] px-3 text-sm text-white transition hover:border-[#A92626] hover:text-[#D47272] disabled:opacity-50";
export function PhotosEditor({
photos,
onChange,
inputClass,
labelClass,
cinemaSlug,
}: Props) {
const fileRef = useRef<HTMLInputElement | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [dragging, setDragging] = useState(false);
function updateAt(index: number, value: string) {
onChange(photos.map((item, i) => (i === index ? value : item)));
}
async function uploadFiles(files: FileList | File[]) {
const list = Array.from(files).filter((file) => file.size > 0);
if (list.length === 0) return;
const tooBig = list.find((file) => file.size > MAX_UPLOAD_BYTES);
if (tooBig) {
setError(
`ไฟล์ "${tooBig.name}" ใหญ่เกิน ${Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MB`,
);
return;
}
setBusy(true);
setError(null);
const uploaded: string[] = [];
try {
for (const file of list) {
const form = new FormData();
form.append("file", file);
if (cinemaSlug) form.append("slug", cinemaSlug);
const res = await fetch("/api/admin/uploads", {
method: "POST",
body: form,
});
if (!res.ok) {
const message = await res.text();
throw new Error(message || `อัปโหลดไม่สำเร็จ (${res.status})`);
}
const data = (await res.json()) as { url?: string };
if (!data.url) throw new Error("เซิร์ฟเวอร์ไม่ได้คืน URL ของรูป");
uploaded.push(data.url);
}
if (uploaded.length > 0) onChange([...photos, ...uploaded]);
} catch (uploadError) {
setError(
uploadError instanceof Error ? uploadError.message : "อัปโหลดไม่สำเร็จ",
);
} finally {
setBusy(false);
if (fileRef.current) fileRef.current.value = "";
}
}
return (
<div
className={`flex flex-col gap-2 rounded-lg border border-dashed p-2 transition ${
dragging ? "border-[#A92626] bg-[#1B1B1B]/60" : "border-transparent"
}`}
onDragOver={(event) => {
if (!event.dataTransfer?.types.includes("Files")) return;
event.preventDefault();
setDragging(true);
}}
onDragLeave={() => setDragging(false)}
onDrop={(event) => {
if (!event.dataTransfer?.files?.length) return;
event.preventDefault();
setDragging(false);
void uploadFiles(event.dataTransfer.files);
}}
onPaste={(event) => {
const files = Array.from(event.clipboardData?.files ?? []);
if (files.length === 0) return;
event.preventDefault();
void uploadFiles(files);
}}
>
<span className="text-xs text-[#999]">รูปภาพโรงหนัง</span>
{photos.length === 0 ? (
<span className="text-[11px] text-[#777]">
ยังไม่มีรูป — อัปโหลดจากเครื่อง หรือวาง URL ด้านล่าง (ภาพที่ 1/2/3)
</span>
) : null}
{photos.map((photo, index) => (
<div
key={index}
className="grid items-center gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-[64px_minmax(0,1fr)_auto_auto]"
>
<div className="size-16 overflow-hidden rounded-md border border-[#303030] bg-[#141414]">
{photo ? (
// eslint-disable-next-line jsx-a11y/alt-text
<img
src={photo}
alt=""
className="size-full object-cover"
loading="lazy"
/>
) : null}
</div>
<label className={labelClass}>
{index === 0 ? "รูปหลัก (URL หรือ /images/...)" : `รูปที่ ${index + 1}`}
<input
className={inputClass}
value={photo}
placeholder="/images/hero.png หรือ https://…/photo.jpg"
onChange={(event) => updateAt(index, event.target.value)}
/>
</label>
<div className="flex gap-1">
<button
type="button"
className={smallButtonClass}
aria-label={`เลื่อนรูปที่ ${index + 1} ขึ้น`}
disabled={index === 0}
onClick={() => {
const next = [...photos];
[next[index - 1], next[index]] = [next[index], next[index - 1]];
onChange(next);
}}
>
↑
</button>
<button
type="button"
className={smallButtonClass}
aria-label={`เลื่อนรูปที่ ${index + 1} ลง`}
disabled={index === photos.length - 1}
onClick={() => {
const next = [...photos];
[next[index + 1], next[index]] = [next[index], next[index + 1]];
onChange(next);
}}
>
↓
</button>
</div>
<button
type="button"
className={smallButtonClass}
aria-label={`ลบรูปที่ ${index + 1}`}
onClick={() => onChange(photos.filter((_, i) => i !== index))}
>
<IconTrash size={14} />
</button>
</div>
))}
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
className={uploadButtonClass}
disabled={busy}
onClick={() => fileRef.current?.click()}
>
<IconPhotoUp size={16} />
{busy ? "กำลังอัปโหลด…" : "อัปโหลดรูปจากเครื่อง"}
</button>
<button
type="button"
className={`${smallButtonClass} w-fit`}
onClick={() => onChange([...photos, ""])}
>
<IconPlus size={14} />
เพิ่มช่อง URL
</button>
<span className="text-[11px] text-[#777]">
ลากไฟล์มาวาง หรือ Ctrl+V ในกล่องนี้ · JPG/PNG/WebP/AVIF ≤{" "}
{Math.round(MAX_UPLOAD_BYTES / 1024 / 1024)} MB
</span>
</div>
<input
ref={fileRef}
type="file"
accept="image/jpeg,image/png,image/webp,image/avif"
multiple
className="hidden"
onChange={(event) => {
if (event.target.files) void uploadFiles(event.target.files);
}}
/>
{error ? (
<span role="alert" className="text-[11px] text-[#D47272]">
{error}
</span>
) : null}
</div>
);
}