feat(app): JSON-driven theaters, admin CRUD with login, hidden flag, image upload, PWA

This commit is contained in:
BANK committed 2026-10-27 22:24:30 +07:00
1 parent 44823a5b90
commit 5fdd78acc6
22 files changed
+2668 -108

No files matched your search

+1
View File
@@ -44,3 +44,4 @@ desktop.ini
# temp
.tmp/
*.local
/New folder/
+6 -1
View File
@@ -30,14 +30,19 @@ dist-ssr
!.env.example
.tmp/
**/data/
/data/
data/pglite/
data/uploads/
data/settings.json
data/.sessions.json
# ข้อมูลโรงหนังเป็นเนื้อหาของเว็บ (ไม่ใช่ local data) — ต้อง commit
!public/data/
!public/data/theaters.json
learnings.md
.vercel/
.agent-native/
data/*.lock
public/data/theaters.backup.json
+21 -1
View File
@@ -9,7 +9,6 @@ that direction: once filled in, read and preserve them on every build; while
they are still empty, the first substantial UI pass fills them in.
## Non-negotiable: impress by default
When this app is still a blank canvas, every app generated from this template
must look **spectacular on first load**, even when the build prompt gives no
design direction. "Looks like a clean, intentional product" is the floor, not
@@ -65,3 +64,24 @@ Surface And Page Boundaries so the surfaces are wired correctly.
- Density comes from data, not prose. Subtract explanatory chrome; never
subtract the visual craft that makes the app impressive.
- Compare against real products in the chosen mode, not against the starter.
## AlterFlixHub — ของจริงที่ใช้อยู่ (อัปเดต 2026-10-27)
**แบรนด์:** แดง #8F0808, พื้นดำ #0D0D0D, การ์ด #1B1B1B, เส้นขอบ #2A2A2A/#332B2B
โลโก้ฟอนต์ Jersey 15 (มีเฉพาะชื่อแบรนด์) · เนื้อหาไทยใช้ Inter + Noto Sans Thai
**หน้าเว็บ**
- `/` หน้าแรก: hero + ช่องค้นหา + การ์ดโรงหนัง (การ์ดมีรูป = รูปปก + gradient ทับให้ตัวหนังสืออ่านออก)
- `/cinema/:slug` รายละเอียด: รูปใหญ่ + ป้ายหมวด + ข้อมูลเดินทาง/ติดต่อ/สิ่งอำนวยความสะดวก + "โรงหนังอิสระอื่นๆ"
- `/admin` หลังบ้าน (ต้องล็อกอินที่ `/admin/login`): ฟอร์มแก้ข้อมูล, อัปโหลดรูป, ปุ่มซ่อน/แสดง, ลบโรง
- `/single` เก็บหน้าเวอร์ชันเดิม (single-page + detail sheet) ไว้เทียบ
**สถานะการซ่อน:** `hidden: true` ใน JSON = ไม่ขึ้นหน้าแรก/ตัวนับ แต่เปิดด้วย URL ตรงได้ และขึ้นป้าย "ซ่อนจากหน้าแรก" ที่หน้ารายละเอียด
**รูปโรงหนัง:** เก็บไฟล์จริงที่ `public/images/theaters/` ผ่าน `/admin/image` (JPG/PNG/WebP/AVIF ≤ 6 MB)
ใช้ `object-cover` + กันที่ด้วย aspect ratio (การ์ด 3:4 / รูปใหญ่ 269:202) → ไม่เกิด layout shift
รูปการ์ดใช้ `loading="lazy"` (อยู่ใต้ fold) รูปใหญ่หน้ารายละเอียดโหลดทันที
**คอนทราสต์ที่วัดแล้ว (WCAG)**: #B3B3B3/#111 = 8.9:1 · #e0b357/#2a1f00 = 8.4:1 · #ff9a9a/#111 = 9.4:1 · ขาว/#8F0808 = 9.1:1 — ผ่าน AA ทั้งหมด
**PWA:** `public/sw.js` (network-first หน้าเว็บ + `/data/`, cache-first assets, ข้าม `/_agent-native/`), bump `CACHE_VERSION` เมื่อแก้ asset, manifest ผูก `/icon-192.svg` + `/icon-512.svg`
+101
View File
@@ -0,0 +1,101 @@
import crypto from "node:crypto";
import { redirect } from "react-router";
/**
* ยืนยันตัวตนสำหรับหน้าหลังบ้าน (/admin)
* ------------------------------------------------------------
* ★ ผู้ใช้/รหัสค่าเริ่มต้น: it's me / it's me&it's me (override ด้วย env ได้)
* ★ session = cookie HttpOnly เซ็นด้วย HMAC — ไม่เก็บรหัสใน cookie
* ★ อายุ session 12 ชั่วโมง
* ★ ใช้ฝั่ง server เท่านั้น (ห้าม import ใน component ฝั่ง client)
*/
export const ADMIN_USERNAME = process.env.ADMIN_USERNAME ?? "it's me";
export const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD ?? "it's me&it's me";
const SECRET =
process.env.ADMIN_SESSION_SECRET ?? "alterflixhub-dev-secret-please-change";
const COOKIE_NAME = "alterflix_admin";
const MAX_AGE_SECONDS = 60 * 60 * 12;
function sign(payload: string): string {
return crypto.createHmac("sha256", SECRET).update(payload).digest("base64url");
}
function safeEqual(a: string, b: string): boolean {
const ha = crypto.createHash("sha256").update(a).digest();
const hb = crypto.createHash("sha256").update(b).digest();
return crypto.timingSafeEqual(ha, hb);
}
export function verifyCredentials(username: string, password: string): boolean {
return safeEqual(username, ADMIN_USERNAME) && safeEqual(password, ADMIN_PASSWORD);
}
export function createSessionCookie(): string {
const expires = Date.now() + MAX_AGE_SECONDS * 1000;
const payload = `${ADMIN_USERNAME}.${expires}`;
const token = `${Buffer.from(payload).toString("base64url")}.${sign(payload)}`;
const parts = [
`${COOKIE_NAME}=${token}`,
"Path=/",
"HttpOnly",
"SameSite=Lax",
`Max-Age=${MAX_AGE_SECONDS}`,
];
return parts.join("; ");
}
export function clearSessionCookie(): string {
return `${COOKIE_NAME}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`;
}
function readCookie(request: Request, name: string): string | null {
const header = request.headers.get("cookie");
if (!header) return null;
for (const chunk of header.split(";")) {
const [key, ...rest] = chunk.trim().split("=");
if (key === name) return rest.join("=");
}
return null;
}
export type AdminSession = { username: string; expires: number };
export function getSession(request: Request): AdminSession | null {
const token = readCookie(request, COOKIE_NAME);
if (!token) return null;
const [encodedPayload, signature] = token.split(".");
if (!encodedPayload || !signature) return null;
let payload: string;
try {
payload = Buffer.from(encodedPayload, "base64url").toString("utf8");
} catch {
return null;
}
if (!safeEqual(signature, sign(payload))) return null;
const [username, expiresRaw] = payload.split(".");
const expires = Number(expiresRaw);
if (!username || !Number.isFinite(expires) || expires < Date.now()) return null;
return { username, expires };
}
/** ใช้ใน loader/action ของหน้าที่ต้องล็อกอิน — เด้งไป /login ถ้ายังไม่มี session */
export function requireAdmin(request: Request): AdminSession {
const session = getSession(request);
if (!session) {
const url = new URL(request.url);
const next = `${url.pathname}${url.search}`;
throw redirect(`/admin/login?next=${encodeURIComponent(next)}`);
}
return session;
}
/** ตรวจจาก handler ที่ไม่ใช่ loader (เช่น API) — คืน true/false */
export function isAdminRequest(request: Request): boolean {
return getSession(request) !== null;
}
+88
View File
@@ -0,0 +1,88 @@
import fs from "node:fs/promises";
import path from "node:path";
/**
* จัดการไฟล์รูปโรงหนัง (ฝั่ง server เท่านั้น)
* ------------------------------------------------------------
* ★ เก็บที่ public/images/theaters/ → เสิร์ฟเป็น /images/theaters/<ไฟล์>
* ★ รับเฉพาะ jpeg/png/webp/avif และไม่เกิน 6 MB
* ★ ชื่อไฟล์부터 slug + เวลา → อัปรูปซ้ำได้ ไม่ทับของเก่า (แล้วลบไฟล์เก่าให้)
* ★ ตรวจ path ก่อนลบ — ลบได้เฉพาะไฟล์ในโฟลเดอร์ของตัวเอง
*/
const IMAGE_DIR = path.join(process.cwd(), "public", "images", "theaters");
const PUBLIC_PREFIX = "/images/theaters/";
const MIME_EXT: Record<string, string> = {
"image/jpeg": "jpg",
"image/jpg": "jpg",
"image/png": "png",
"image/webp": "webp",
"image/avif": "avif",
};
export const MAX_IMAGE_BYTES = 6 * 1024 * 1024;
export const ACCEPTED_MIME = Object.keys(MIME_EXT);
export const ACCEPT_ATTR = ".jpg,.jpeg,.png,.webp,.avif,image/jpeg,image/png,image/webp,image/avif";
export type ImageSaveResult =
| { ok: true; url: string; bytes: number }
| { ok: false; message: string };
function safeSlug(slug: string): string {
const cleaned = slug
.toLowerCase()
.replace(/[^a-z0-9-]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60);
return cleaned || "theater";
}
export async function saveTheaterImage(
slug: string,
file: File,
): Promise<ImageSaveResult> {
const ext = MIME_EXT[file.type.toLowerCase()];
if (!ext) {
return {
ok: false,
message: "รองรับเฉพาะไฟล์ JPG, PNG, WebP หรือ AVIF",
};
}
if (file.size === 0) return { ok: false, message: "ไฟล์ว่าง" };
if (file.size > MAX_IMAGE_BYTES) {
return { ok: false, message: "ไฟล์ใหญ่เกิน 6 MB" };
}
await fs.mkdir(IMAGE_DIR, { recursive: true });
const filename = `${safeSlug(slug)}-${Date.now()}.${ext}`;
const buffer = Buffer.from(await file.arrayBuffer());
await fs.writeFile(path.join(IMAGE_DIR, filename), buffer);
return { ok: true, url: `${PUBLIC_PREFIX}${filename}`, bytes: buffer.byteLength };
}
/** ลบรูปเดิม (เฉพาะ path ที่อยู่ใน /images/theaters/) — ใช้ตอนอัปใหม่หรือกดลบรูป */
export async function deleteTheaterImage(url: string | null): Promise<boolean> {
if (!url || !url.startsWith(PUBLIC_PREFIX)) return false;
const filename = url.slice(PUBLIC_PREFIX.length);
if (!filename || filename.includes("/") || filename.includes("..")) return false;
try {
await fs.unlink(path.join(IMAGE_DIR, filename));
return true;
} catch {
return false;
}
}
/** รายชื่อไฟล์รูปที่เก็บไว้ (ใช้นับ/ตรวจในหน้าหลังบ้าน) */
export async function listTheaterImages(): Promise<string[]> {
try {
const files = await fs.readdir(IMAGE_DIR);
return files.filter((name) => MIME_EXT[`image/${name.split(".").pop()}`] ?? true);
} catch {
return [];
}
}
+85
View File
@@ -0,0 +1,85 @@
import fs from "node:fs/promises";
import path from "node:path";
import type { Theater, TheatersFile } from "./theaters";
import { validateTheatersFile } from "./theaters";
/**
* ชั้นอ่าน/เขียนไฟล์ JSON (ใช้ฝั่ง server เท่านั้น)
* ------------------------------------------------------------
* ★ ข้อมูลจริงอยู่ที่ public/data/theaters.json (อ่านง่าย แก้มือได้)
* ★ ก่อนเขียนทุกครั้ง สำรองของเดิมไว้ที่ theaters.backup.json
* ★ หน้าบ้าน (loader) อ่านผ่าน readTheatersFile() — ไม่มีสำเนาข้อมูลในโค้ด
*/
const DATA_DIR = path.join(process.cwd(), "public", "data");
const FILE_PATH = path.join(DATA_DIR, "theaters.json");
const BACKUP_PATH = path.join(DATA_DIR, "theaters.backup.json");
const EMPTY_FILE: TheatersFile = {
updated_at: new Date().toISOString(),
theaters: [],
};
export function theatersFilePath(): string {
return FILE_PATH;
}
export async function readTheatersFile(): Promise<TheatersFile> {
try {
const raw = await fs.readFile(FILE_PATH, "utf8");
const parsed = JSON.parse(raw) as TheatersFile;
const error = validateTheatersFile(parsed);
if (error) {
return { ...EMPTY_FILE, updated_at: new Date().toISOString() };
}
return {
updated_at: parsed.updated_at ?? new Date().toISOString(),
theaters: parsed.theaters,
};
} catch {
return { ...EMPTY_FILE, updated_at: new Date().toISOString() };
}
}
export async function readTheaters(): Promise<Theater[]> {
const file = await readTheatersFile();
return file.theaters;
}
export type WriteResult = {
saved: number;
updated_at: string;
backup_created: boolean;
};
/** เขียนทับไฟล์ข้อมูล — สำรองของเดิมก่อนเสมอ */
export async function writeTheaters(theaters: Theater[]): Promise<WriteResult> {
const error = validateTheatersFile({ theaters });
if (error) throw new Error(error);
await fs.mkdir(DATA_DIR, { recursive: true });
let backupCreated = false;
try {
await fs.copyFile(FILE_PATH, BACKUP_PATH);
backupCreated = true;
} catch {
backupCreated = false;
}
const next: TheatersFile = {
updated_at: new Date().toISOString(),
theaters,
};
// เขียนแบบ JSON อ่านง่าย: 2 spaces + CRLF ปิดท้ายไฟล์
const text = `${JSON.stringify(next, null, 2)}\n`;
await fs.writeFile(FILE_PATH, text, "utf8");
return {
saved: theaters.length,
updated_at: next.updated_at,
backup_created: backupCreated,
};
}
+156
View File
@@ -0,0 +1,156 @@
import {
IconBook,
IconBriefcase,
IconBus,
IconCoffee,
IconPlant2,
IconShoppingBag,
IconSofa,
IconTicket,
IconToolsKitchen2,
IconTrain,
} from "@tabler/icons-react";
import type { ComponentType } from "react";
/** ---------- ชนิดข้อมูล (ตรงกับ public/data/theaters.json) ---------- */
export type TheaterTransport = {
/** ชื่อไอคอนใน ICONS */
icon: string;
label: string;
value: string;
};
export type TheaterContact = { label: string; value: string };
export type TheaterFacility = {
/** ชื่อไอคอนใน ICONS */
icon: string;
title: string;
sub: string;
};
export type Theater = {
/** ใช้ใน URL: /cinema/<slug> */
slug: string;
name: string;
area: string;
distance: string;
categories: string[];
/** null = ยังไม่มีข้อมูลรายละเอียด */
description: string | null;
address: string | null;
map_url: string | null;
transport: TheaterTransport[];
contacts: TheaterContact[];
payments: string[];
facilities: TheaterFacility[];
/** true = ซ่อนจากหน้าแรก/รายการสาธารณะ (ยังเปิดดูด้วย URL ตรงได้) */
hidden: boolean;
/** รูปปกโรงหนัง — path ในเว็บ (/images/theaters/...) หรือ URL เต็ม; null = ใช้พื้นหลังไล่สี */
image: string | null;
};
export type TheatersFile = {
updated_at: string;
theaters: Theater[];
};
/** ที่อยู่ไฟล์ข้อมูล (public/) — ใช้ทั้งตอนอ่านฝั่ง server และ fetch ฝั่ง client */
export const THEATERS_JSON_PATH = "/data/theaters.json";
/** ---------- ไอคอน ---------- */
type IconComponent = ComponentType<{ size?: number; stroke?: number }>;
export const ICONS: Record<string, IconComponent> = {
bus: IconBus,
train: IconTrain,
sofa: IconSofa,
ticket: IconTicket,
food: IconToolsKitchen2,
cafe: IconCoffee,
garden: IconPlant2,
book: IconBook,
workspace: IconBriefcase,
shop: IconShoppingBag,
};
/** รายชื่อไอคอนที่เลือกได้ในหน้าหลังบ้าน */
export const ICON_NAMES = Object.keys(ICONS);
export function resolveIcon(name: string): IconComponent | null {
return ICONS[name] ?? null;
}
/** ---------- ตัวช่วย ---------- */
export function getTheater(
theaters: Theater[],
slug: string | undefined,
): Theater | undefined {
if (!slug) return undefined;
return theaters.find((theater) => theater.slug === slug);
}
/** สร้าง slug จากชื่อโรง — ใช้ตอนเพิ่มโรงใหม่ในหน้าหลังบ้าน */
export function toSlug(name: string): string {
return name
.trim()
.toLowerCase()
.replace(/[^a-z0-9ก-๙]+/g, "-")
.replace(/^-+|-+$/g, "");
}
export const CATEGORY_OPTIONS = [
"ยอดนิยม",
"อาร์ตเฮาส์",
"สารคดี",
"หนังสั้น",
"หนังคลาสสิก",
"หนังนานาชาติ",
"หนังนอกกระแส",
"หนังในกระแส",
"หนังฝรั่งเศส",
];
export function emptyTheater(name = "โรงหนังใหม่"): Theater {
return {
slug: toSlug(name) || `theater-${Date.now()}`,
name,
area: "",
distance: "—",
categories: [],
description: null,
address: null,
map_url: null,
transport: [],
contacts: [],
payments: [],
facilities: [],
hidden: false,
image: null,
};
}
/** ตรวจโครงสร้างไฟล์ JSON — คืน null ถ้าผ่าน, คืนข้อความถ้าไม่ผ่าน */
export function validateTheatersFile(value: unknown): string | null {
if (!value || typeof value !== "object") return "ไฟล์ต้องเป็น object";
const file = value as Partial<TheatersFile>;
if (!Array.isArray(file.theaters)) return "ต้องมีคีย์ theaters เป็น array";
const slugs = new Set<string>();
for (const [i, theater] of file.theaters.entries()) {
if (!theater || typeof theater !== "object") {
return `รายการที่ ${i + 1} ไม่ใช่ object`;
}
if (typeof theater.slug !== "string" || !theater.slug) {
return `รายการที่ ${i + 1} ไม่มี slug`;
}
if (slugs.has(theater.slug)) return `slug ซ้ำ: ${theater.slug}`;
slugs.add(theater.slug);
if (typeof theater.name !== "string" || !theater.name) {
return `รายการที่ ${i + 1} ไม่มี name`;
}
}
return null;
}
+45 -1
View File
@@ -5,7 +5,7 @@ import { createAgentNativeQueryClient } from "@agent-native/core/client/hooks";
import { getThemeInitScript } from "@agent-native/core/client/ui";
import { AppProviders } from "@agent-native/toolkit/app/providers";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useEffect, useState } from "react";
import { Links, Meta, Outlet, Scripts, ScrollRestoration } from "react-router";
import type { LinksFunction } from "react-router";
@@ -26,8 +26,51 @@ configureTracking({
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: stylesheet },
{ rel: "manifest", href: appPath("/manifest.json") },
];
/** ลงทะเบียน Service Worker — อัปเดตแล้ว reload ครั้งเดียวเมื่อตัวใหม่เข้าคุมหน้า */
function useServiceWorker() {
useEffect(() => {
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) {
return;
}
let reloaded = false;
const onControllerChange = () => {
if (reloaded) return;
reloaded = true;
window.location.reload();
};
navigator.serviceWorker.addEventListener(
"controllerchange",
onControllerChange,
);
navigator.serviceWorker
.register("/sw.js", { scope: "/" })
.then((registration) => {
registration.addEventListener("updatefound", () => {
const installing = registration.installing;
installing?.addEventListener("statechange", () => {
if (
installing.state === "installed" &&
navigator.serviceWorker.controller
) {
installing.postMessage("SKIP_WAITING");
}
});
});
})
.catch(() => undefined);
return () => {
navigator.serviceWorker.removeEventListener(
"controllerchange",
onControllerChange,
);
};
}, []);
}
const THEME_INIT_SCRIPT = getThemeInitScript();
export function Layout({ children }: { children: React.ReactNode }) {
@@ -79,6 +122,7 @@ function DbSyncSetup() {
export default function Root() {
const [queryClient] = useState(() => createAgentNativeQueryClient());
useServiceWorker();
return (
<AppToolkitProvider>
<AppProviders queryClient={queryClient}>
+224 -79
View File
@@ -1,115 +1,260 @@
import { useEffect } from "react";
import { useSearchParams } from "react-router";
import { useState } from "react";
import {
IconArrowRight,
IconBrandFacebook,
IconBrandInstagram,
IconBrandLinkedin,
IconBrandTelegram,
IconBrandYoutube,
IconBuildingCommunity,
IconChevronDown,
IconMapPin,
IconSearch,
IconSettings,
} from "@tabler/icons-react";
import { Link, useLoaderData } from "react-router";
import { CINEMAS, getCinema } from "@/lib/cinemas";
import { useLang } from "@/lib/i18n";
import { CinemaCard } from "@/components/cinema/CinemaCard";
import { CinemaDetailSheet } from "@/components/cinema/CinemaDetailSheet";
import { SiteFooter, SiteHeader } from "@/components/cinema/SiteHeader";
import { readTheatersFile } from "@/lib/theaters-store.server";
import type { Theater } from "@/lib/theaters";
export function meta() {
return [
{ title: "AlterFlixHub — โรงภาพยนตร์" },
{ title: "AlterFlixHub — โรงหนังอิสระ" },
{
name: "description",
content: "เลือกโรงภาพยนตร์ที่ใช่ ดูรอบฉายและรายละเอียดได้ในที่เดียว",
content: "ค้นหาโรงภาพยนตร์อิสระ ทางเลือกในการดูหนัง",
},
];
}
/** อ่านข้อมูลจาก public/data/theaters.json ทุกครั้งที่มี request */
export async function loader() {
const file = await readTheatersFile();
return { theaters: file.theaters, updatedAt: file.updated_at };
}
const HERO_IMAGE =
"https://api.builder.io/api/v1/image/assets/TEMP/9e066417bc0d24ee206fcf20fd53ef301362fdc4?width=2880";
const CATEGORIES = [
"ทั้งหมด",
"ยอดนิยม",
"อาร์ตเฮาส์",
"สารคดี",
"หนังสั้น",
"หนังคลาสสิก",
"หนังนานาชาติ",
"หนังนอกกระแส",
"หนังในกระแส",
"หนังฝรั่งเศส",
];
const SOCIALS = [
IconBrandFacebook,
IconBrandInstagram,
IconBrandLinkedin,
IconBrandYoutube,
IconBrandTelegram,
];
const CARD_GRADIENTS = [
"from-[#3a2a22] via-[#2a2a3a] to-[#1b1b1b]",
"from-[#2a2a3a] via-[#1f2a3a] to-[#1b1b1b]",
"from-[#3a3a4a] via-[#2a2a2a] to-[#1b1b1b]",
"from-[#4a3320] via-[#2a2a2a] to-[#1b1b1b]",
];
function Logo({ className = "" }: { className?: string }) {
return (
<Link to="/" className={`shrink-0 ${className}`} aria-label="AlterFlixHub">
<span className="font-['Jersey_15'] text-4xl leading-none text-[#8F0808]">
AlterFlixHub
</span>
</Link>
);
}
/**
* หน้าแรก (Home) — รายการโรงภาพยนตร์ + รายละเอียดในหน้าเดียวกัน
* ------------------------------------------------------------
* ★ เว็บหน้าเดียว: การ์ด → เปิด sheet ทับ ไม่เปลี่ยน route, ไม่รีเฟรช
* รายการด้านหลังไม่ unmount → scroll ที่เลื่อนไว้ยังอยู่
* ★ URL = /?cinema=<slug> (pushState) → แชร์ลิงก์ได้, back ปิด sheet
* ★ มือถือ 6" (360–430px): การ์ด 1 คอลัมน์แนวนอน, sheet เต็มจอ
* ★ แท็บเล็ต (640–1023px): 2 คอลัมน์
* ★ เดสก์ท็อป (≥1024px): 3 คอลัมน์, sheet กลางจอ
* หน้าแรก — รายการโรงหนังอิสระ (อ่านจาก JSON)
* ★ การ์ดลิงก์ไป /cinema/<slug>
* ★ ปุ่มหมวดกรองฝั่ง client
* ★ ลิงก์ "จัดการข้อมูล" → /admin (ระบบหลังบ้าน)
*/
export default function HomeRoute() {
const { t } = useLang();
const [searchParams, setSearchParams] = useSearchParams();
const activeSlug = searchParams.get("cinema");
const activeCinema = getCinema(activeSlug ?? undefined);
/** เปิดรายละเอียด — push history entry (ปุ่ม back ของเบราว์เซอร์จะปิด sheet) */
const openCinema = (slug: string) => {
setSearchParams({ cinema: slug });
const { theaters: all } = useLoaderData() as {
theaters: Theater[];
updatedAt: string;
};
const [active, setActive] = useState(CATEGORIES[0]);
/** ปิด — replace เพื่อไม่ให้ history บวมด้วย entry ของ state "ปิด" */
const closeCinema = () => {
setSearchParams({}, { replace: true });
};
// โรงที่ถูกซ่อนในหลังบ้าน (hidden=true) ไม่ขึ้นหน้าแรก
const visible = all.filter((theater) => !theater.hidden);
/* title เปลี่ยนตามโรงที่เปิด — ลิงก์ที่แชร์จะได้ชื่อถูก */
useEffect(() => {
document.title = activeCinema
? `${activeCinema.name} — AlterFlixHub`
: "AlterFlixHub — โรงภาพยนตร์";
}, [activeCinema]);
const theaters =
active === "ทั้งหมด"
? visible
: visible.filter((theater) => theater.categories.includes(active));
return (
<div className="relative min-h-full bg-gradient-to-b from-[#0a0a0a] via-[#160505] to-[#0a0a0a] text-white">
{/* แสงแดงเรือง ๆ หลัง hero — decorative */}
<div
className="pointer-events-none absolute left-1/2 top-20 h-56 w-56 -translate-x-1/2 rounded-full opacity-50 blur-[110px] sm:top-28 sm:h-80 sm:w-80 sm:blur-[140px]"
style={{ background: "#4C0404" }}
aria-hidden="true"
<div className="relative min-h-screen w-full overflow-x-hidden bg-[#0D0D0D] text-white">
<img
src={HERO_IMAGE}
alt=""
className="pointer-events-none absolute inset-x-0 top-0 h-[553px] w-full object-cover"
/>
<div className="pointer-events-none absolute inset-x-0 top-0 h-[553px] bg-gradient-to-b from-transparent via-[#0D0D0D]/60 to-[#0D0D0D]" />
<div className="pointer-events-none absolute left-1/2 top-0 size-[382px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-[#8F0808] blur-[237px]" />
<div className="pointer-events-none absolute left-1/2 top-[1620px] size-[382px] -translate-x-1/2 rounded-full bg-[#4C0404]/70 blur-[237px]" />
<SiteHeader />
<main className="relative mx-auto w-full max-w-[1160px] px-4 pb-10 sm:px-5 sm:pb-14">
{/* ---------- Hero ---------- */}
<section className="py-8 text-center sm:py-12 lg:py-16">
<h1 className="mx-auto max-w-[22ch] text-[28px] font-black leading-[1.2] tracking-tight sm:text-[38px] lg:text-[48px]">
<header className="relative z-10 mx-auto flex h-[68px] max-w-[1440px] items-center justify-between px-5 md:px-[108px]">
<Logo />
<div className="flex items-center gap-4">
<Link
to="/admin"
className="flex items-center gap-2 rounded-lg border border-[#303030] px-3 py-1.5 text-sm text-[#B3B3B3] transition hover:border-[#A92626] hover:text-white"
>
<IconSettings size={16} />
จัดการข้อมูล
</Link>
<button className="flex items-center gap-2 text-lg font-medium">
<span
className="bg-clip-text text-transparent"
className="block h-4 w-[21px] shrink-0 rounded-[1px]"
style={{
backgroundImage:
"linear-gradient(135deg,#ff1f1f 0%,#e00000 45%,#7a0000 100%)",
background:
"linear-gradient(#A51931 0 17%, #F4F5F8 17% 34%, #2D2A4A 34% 66%, #F4F5F8 66% 83%, #A51931 83%)",
}}
>
{t("home.hero1")}
</span>
<br />
{t("home.hero2")}
</h1>
<p className="mx-auto mt-3 max-w-[40ch] text-sm leading-relaxed text-[#9ca3af] sm:mt-4 sm:max-w-[52ch] sm:text-base">
{t("home.lead")}
</p>
/>
TH
<IconChevronDown size={16} />
</button>
</div>
</header>
<main className="relative z-10 mx-auto max-w-[1440px] px-5 md:px-[108px]">
<section className="mx-auto flex max-w-[1016px] flex-col items-center gap-10 pt-24 md:pt-[167px]">
<div className="flex max-w-[745px] flex-col items-center gap-4 text-center">
<h1 className="text-4xl font-bold leading-[1.3] md:text-[56px]">
ค้นพบ<span className="text-[#A92626]">โรงหนังอิสระ</span>ใกล้คุณ
</h1>
<p className="text-base md:text-xl">
ค้นหาโรงภาพยนตร์อิสระ ทางเลือกในการดูหนัง
</p>
</div>
<div className="w-full rounded-2xl border border-[#303030] bg-[#1B1B1B]/80 px-4 py-6 backdrop-blur-[32px] md:px-10">
<div className="flex h-14 items-center gap-3 rounded-lg border border-[#1B1B1B] bg-[#1F1F1F] px-5">
<IconSearch size={16} className="shrink-0 text-[#999]" />
<input
placeholder="ค้นหาชื่อโรงหนังหรือสถานที่ / จังหวัด / ประเภทหนัง"
className="min-w-0 flex-1 bg-transparent text-sm text-white outline-none placeholder:text-[#454545]"
/>
<div className="hidden items-center gap-2 border-l border-[#999] px-4 text-sm text-[#999] sm:flex">
<IconMapPin size={16} />
ใกล้ฉัน
</div>
<button className="h-8 rounded-lg border border-[#8F0808] bg-[#8F0808] px-6 text-sm font-medium transition hover:bg-[#a30a0a]">
ค้นหา
</button>
</div>
</div>
</section>
{/* ---------- รายการโรงภาพยนตร์ ---------- */}
<section aria-labelledby="cinemas-heading">
<div className="mb-3 flex items-baseline gap-2 sm:mb-4">
<h2 id="cinemas-heading" className="text-lg font-extrabold sm:text-xl">
{t("home.sectionTitle")}
</h2>
<span className="text-xs text-[#9ca3af] sm:text-sm">
{t("home.count", { n: CINEMAS.length })}
<section className="mt-16 flex flex-col gap-6 md:mt-[65px]">
<div className="flex h-[72px] items-center border-b border-[#1F1F1F] py-2">
<h2 className="text-[28px] font-semibold">รายชื่อโรงหนังอิสระ</h2>
<span className="ml-3 text-sm text-[#B3B3B3]">
{visible.length} โรง
</span>
</div>
{/* มือถือ = 1 คอลัมน์ · แท็บเล็ต = 2 · เดสก์ท็อป = 3 */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3">
{CINEMAS.map((cinema) => (
<CinemaCard key={cinema.slug} cinema={cinema} onSelect={openCinema} />
<div className="flex flex-wrap gap-2">
{CATEGORIES.map((c) => (
<button
key={c}
onClick={() => setActive(c)}
className={
c === active
? "rounded-[18px] border border-[#A92626] bg-gradient-to-b from-[#8F0808]/30 to-[#1B1B1B]/0 px-4 py-2 text-sm text-[#D47272]"
: "rounded-[18px] border border-[#303030] bg-[#242424] px-4 py-2 text-sm text-[#B3B3B3] transition hover:border-[#A92626]/60"
}
>
{c}
</button>
))}
</div>
<div className="mt-2 grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{theaters.map((t, i) => (
<article
key={t.slug}
className={`relative flex aspect-[3/4] flex-col justify-end overflow-hidden rounded-[20px] bg-gradient-to-br p-2 lg:aspect-auto lg:h-[308px] ${CARD_GRADIENTS[i % CARD_GRADIENTS.length]}`}
>
{t.image ? (
<>
<img
src={t.image}
alt={t.name}
loading="lazy"
className="absolute inset-0 h-full w-full object-cover"
/>
<div className="absolute inset-0 bg-gradient-to-t from-black/80 via-black/25 to-transparent" />
</>
) : null}
<div className="relative flex flex-col gap-1.5 rounded-2xl border border-white/10 bg-[#1B1B1B]/80 p-3 backdrop-blur-xl">
<span className="text-[10px] text-[#B3B3B3]">
{t.distance}
</span>
<h3 className="text-sm font-semibold">{t.name}</h3>
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
<IconMapPin size={12} /> {t.area}
</p>
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
<IconBuildingCommunity size={12} />{" "}
{t.categories.join(" · ")}
</p>
<Link
to={`/cinema/${t.slug}`}
className="mt-3 flex items-center justify-end gap-2 text-xs font-medium transition hover:text-[#D47272]"
>
ดูรายละเอียด <IconArrowRight size={12} />
</Link>
</div>
</article>
))}
</div>
{theaters.length === 0 ? (
<p className="py-10 text-center text-sm text-[#B3B3B3]">
ยังไม่มีโรงหนังในหมวดนี้
</p>
) : null}
<div className="flex justify-center pt-2">
<button className="h-10 w-[200px] rounded-lg border border-[#8F0808] bg-[#8F0808] transition hover:bg-[#a30a0a]">
แสดงเพิ่ม
</button>
</div>
</section>
</main>
<SiteFooter />
{/* ---------- รายละเอียด (overlay บนหน้าเดิม) ---------- */}
<CinemaDetailSheet
slug={activeCinema ? activeCinema.slug : null}
onClose={closeCinema}
onSelectCinema={openCinema}
/>
<footer className="relative z-10 mx-auto mt-24 flex max-w-[1440px] flex-col items-center gap-10 px-5 pb-6 md:px-[108px]">
<Logo />
<div className="flex gap-4">
{SOCIALS.map((Icon, i) => (
<a
key={i}
href="#"
className="flex size-[42px] items-center justify-center rounded-full bg-white/90 text-[#0D0D0D] transition hover:bg-white"
>
<Icon size={24} />
</a>
))}
</div>
<div className="mt-24 flex w-full flex-col items-center gap-8">
<div className="h-px w-full bg-white/20" />
<p className="text-sm">Copyright © AlterFlixHub</p>
</div>
</footer>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
import { requireAdmin } from "@/lib/auth.server";
import { deleteTheaterImage, saveTheaterImage } from "@/lib/images.server";
/**
* อัปโหลด / ลบรูปโรงหนัง — /admin/image
* ------------------------------------------------------------
* ★ multipart/form-data: slug + file → บันทึกไฟล์ คืน { ok, url }
* ★ JSON { url } + ?action=delete → ลบไฟล์ คืน { ok, url: null }
* ★ ต้องมี session หลังบ้าน (cookie) ทุกครั้ง
*/
export async function action({ request }: { request: Request }) {
try {
requireAdmin(request);
} catch {
return Response.json(
{ ok: false, message: "ไม่มีสิทธิ์ — กรุณาเข้าสู่ระบบใหม่" },
{ status: 401 },
);
}
const contentType = request.headers.get("content-type") ?? "";
if (contentType.includes("multipart/form-data")) {
const form = await request.formData();
const slug = String(form.get("slug") ?? "");
const file = form.get("image");
if (!slug) {
return Response.json(
{ ok: false, message: "ไม่พบ slug ของโรงหนัง" },
{ status: 400 },
);
}
if (!(file instanceof File)) {
return Response.json(
{ ok: false, message: "ไม่พบไฟล์รูป" },
{ status: 400 },
);
}
const result = await saveTheaterImage(slug, file);
if (!result.ok) {
return Response.json(result, { status: 400 });
}
return Response.json({ ok: true, url: result.url, bytes: result.bytes });
}
const body = (await request.json().catch(() => ({}))) as { url?: string };
const removed = await deleteTheaterImage(body.url ?? null);
return Response.json({ ok: true, url: null, removed });
}
+129
View File
@@ -0,0 +1,129 @@
import { Form, Link, useActionData, useNavigation } from "react-router";
import { IconArrowLeft, IconLock } from "@tabler/icons-react";
import {
createSessionCookie,
verifyCredentials,
} from "@/lib/auth.server";
import { redirect } from "react-router";
/** ปลายทางหลังล็อกอิน — รับเฉพาะ path ในเว็บนี้ (กัน open redirect) */
function safeNext(raw: string | null): string {
if (!raw) return "/admin";
return raw.startsWith("/") && !raw.startsWith("//") ? raw : "/admin";
}
export async function action({ request }: { request: Request }) {
const form = await request.formData();
const username = String(form.get("username") ?? "").trim();
const password = String(form.get("password") ?? "");
const next = safeNext(String(form.get("next") ?? ""));
if (!verifyCredentials(username, password)) {
return {
ok: false,
error: "ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง",
username,
next,
};
}
throw redirect(next, {
headers: { "Set-Cookie": createSessionCookie() },
});
}
export function meta() {
return [{ title: "เข้าสู่ระบบ — AlterFlixHub" }];
}
const inputClass =
"w-full rounded-lg border border-[#303030] bg-[#161616] px-4 py-3 text-sm text-white outline-none transition focus:border-[#A92626]";
export default function LoginRoute() {
const result = useActionData() as
| { ok: false; error: string; username: string; next: string }
| undefined;
const navigation = useNavigation();
const busy = navigation.state === "submitting";
return (
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-[#0D0D0D] px-4 text-white">
<div
className="pointer-events-none absolute left-1/2 top-1/3 size-[420px] -translate-x-1/2 -translate-y-1/2 rounded-full opacity-70 blur-[200px]"
style={{ background: "#8F0808" }}
/>
<div className="relative w-full max-w-[420px]">
<Link
to="/"
className="mb-6 inline-flex items-center gap-2 text-sm text-[#B3B3B3] transition hover:text-white"
>
<IconArrowLeft size={16} /> กลับหน้าเว็บ
</Link>
<div className="rounded-2xl border border-[#2A2A2A] bg-[#111]/90 p-6 backdrop-blur md:p-8">
<div className="flex flex-col items-center gap-2 text-center">
<span className="font-['Jersey_15'] text-4xl leading-none text-[#8F0808]">
AlterFlixHub
</span>
<h1 className="mt-2 flex items-center gap-2 text-lg font-semibold">
<IconLock size={18} /> เข้าสู่ระบบหลังบ้าน
</h1>
<p className="text-xs text-[#888]">
เฉพาะผู้ดูแลเว็บ — ใช้แก้ไขข้อมูลโรงหนังและสถานะการแสดงผล
</p>
</div>
<Form method="post" className="mt-6 flex flex-col gap-4">
<input type="hidden" name="next" value={result?.next ?? "/admin"} />
<label className="flex flex-col gap-1">
<span className="text-xs font-medium text-[#B3B3B3]">
ชื่อผู้ใช้
</span>
<input
name="username"
autoComplete="username"
defaultValue={result?.username ?? ""}
className={inputClass}
placeholder="ชื่อผู้ใช้"
required
/>
</label>
<label className="flex flex-col gap-1">
<span className="text-xs font-medium text-[#B3B3B3]">รหัสผ่าน</span>
<input
name="password"
type="password"
autoComplete="current-password"
className={inputClass}
placeholder="รหัสผ่าน"
required
/>
</label>
{result?.error ? (
<p className="rounded-lg bg-[#3a1113] px-3 py-2 text-sm text-[#ff9a9a]">
{result.error}
</p>
) : null}
<button
type="submit"
disabled={busy}
className="mt-2 h-11 rounded-lg bg-[#8F0808] text-sm font-medium transition hover:bg-[#a30a0a] disabled:opacity-50"
>
{busy ? "กำลังตรวจสอบ…" : "เข้าสู่ระบบ"}
</button>
</Form>
</div>
<p className="mt-4 text-center text-[11px] text-[#555]">
ล็อกอินค้างไว้ 12 ชั่วโมง · ออกจากระบบได้จากหน้าหลังบ้าน
</p>
</div>
</div>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { redirect } from "react-router";
import { clearSessionCookie } from "@/lib/auth.server";
/** ออกจากระบบ — ล้าง cookie แล้วกลับหน้าแรก */
export async function action() {
throw redirect("/", { headers: { "Set-Cookie": clearSessionCookie() } });
}
export async function loader() {
throw redirect("/");
}
export default function LogoutRoute() {
return null;
}
+54
View File
@@ -0,0 +1,54 @@
import type { Theater } from "@/lib/theaters";
import { requireAdmin } from "@/lib/auth.server";
import { writeTheaters } from "@/lib/theaters-store.server";
/**
* บันทึกข้อมูลโรงหนัง — /admin/save (POST JSON)
* ------------------------------------------------------------
* ★ route นี้มีแต่ action ไม่มีหน้า → ตอบ JSON ตรง ไม่ถูก SSR ห่อเป็น HTML
* ★ ต้องมี session หลังบ้าน (cookie) — เขียนไฟล์ได้เฉพาะคนที่ล็อกอิน
* ★ สำรอง theaters.backup.json ก่อนเขียนทุกครั้ง (อยู่ใน writeTheaters)
*/
export async function action({ request }: { request: Request }) {
try {
requireAdmin(request);
} catch {
return Response.json(
{ ok: false, message: "ไม่มีสิทธิ์ — กรุณาเข้าสู่ระบบใหม่" },
{ status: 401 },
);
}
let body: { theaters?: Theater[] };
try {
body = (await request.json()) as { theaters?: Theater[] };
} catch {
return Response.json({ ok: false, message: "อ่าน JSON ไม่ได้" }, { status: 400 });
}
if (!Array.isArray(body.theaters)) {
return Response.json(
{ ok: false, message: "รูปแบบข้อมูลไม่ถูกต้อง" },
{ status: 400 },
);
}
try {
const result = await writeTheaters(body.theaters);
return Response.json({
ok: true,
message: `บันทึกแล้ว ${result.saved} โรง`,
saved: result.saved,
updated_at: result.updated_at,
});
} catch (error) {
return Response.json(
{
ok: false,
message: error instanceof Error ? error.message : "บันทึกไม่สำเร็จ",
},
{ status: 400 },
);
}
}
+17
View File
@@ -0,0 +1,17 @@
import { getSession } from "@/lib/auth.server";
/**
* ตรวจ session ฝั่ง client — /admin/session (POST เท่านั้น)
* ------------------------------------------------------------
* ★ ทำไมต้อง POST: ตัวจัดการ .data/SSR ของ agent-native ตัด Cookie header ออก
* เหลือแค่ accept/connection/host/user-agent → loader อ่าน cookie ไม่ได้
* แต่ action (POST) ยังได้ header ครบ ⇒ ใช้ POST เป็นช่องตรวจสิทธิ์
* ★ การเขียนข้อมูล (บันทึก/อัปรูป) ถูกบังคับสิทธิ์ที่ action ฝั่ง server อยู่แล้ว
*/
export async function action({ request }: { request: Request }) {
const session = getSession(request);
return Response.json({
authenticated: !!session,
username: session?.username ?? null,
});
}
+860
View File
@@ -0,0 +1,860 @@
import { useEffect, useMemo, useState } from "react";
import {
IconArrowLeft,
IconDeviceFloppy,
IconEye,
IconEyeOff,
IconLogout,
IconPlus,
IconRefresh,
IconTrash,
} from "@tabler/icons-react";
import {
Form,
Link,
useLoaderData,
useRevalidator,
} from "react-router";
import type {
Theater,
TheaterContact,
TheaterFacility,
TheaterTransport,
} from "@/lib/theaters";
import { CATEGORY_OPTIONS, ICON_NAMES, emptyTheater, toSlug } from "@/lib/theaters";
import { readTheatersFile } from "@/lib/theaters-store.server";
export async function loader() {
const file = await readTheatersFile();
return { theaters: file.theaters, updatedAt: file.updated_at };
}
/** บันทึกข้อมูล — ย้ายไป route /admin/save (action-only ตอบ JSON ตรง) */
export function meta() {
return [{ title: "จัดการข้อมูล — AlterFlixHub" }];
}
const SAVE_ENDPOINT = "/admin/save";
const inputClass =
"w-full rounded-lg border border-[#303030] bg-[#161616] px-3 py-2 text-sm text-white outline-none focus:border-[#A92626]";
const labelClass = "text-xs font-medium text-[#B3B3B3]";
const panelClass = "rounded-xl border border-[#2A2A2A] bg-[#111] p-4";
function Field({
label,
value,
onChange,
placeholder,
}: {
label: string;
value: string;
onChange: (value: string) => void;
placeholder?: string;
}) {
return (
<label className="flex flex-col gap-1">
<span className={labelClass}>{label}</span>
<input
className={inputClass}
value={value}
placeholder={placeholder}
onChange={(event) => onChange(event.target.value)}
/>
</label>
);
}
function Area({
label,
value,
onChange,
rows = 3,
}: {
label: string;
value: string;
onChange: (value: string) => void;
rows?: number;
}) {
return (
<label className="flex flex-col gap-1">
<span className={labelClass}>{label}</span>
<textarea
className={inputClass}
rows={rows}
value={value}
onChange={(event) => onChange(event.target.value)}
/>
</label>
);
}
/** ช่องกรอกหลายค่า (คั่นด้วยจุลภาค) */
function CsvField({
label,
values,
onChange,
}: {
label: string;
values: string[];
onChange: (values: string[]) => void;
}) {
return (
<Field
label={label}
value={values.join(", ")}
placeholder="คั่นด้วยจุลภาค"
onChange={(text) =>
onChange(
text
.split(",")
.map((part) => part.trim())
.filter(Boolean),
)
}
/>
);
}
export default function AdminRoute() {
const data = useLoaderData() as { theaters: Theater[]; updatedAt: string };
const revalidator = useRevalidator();
const [list, setList] = useState<Theater[]>(data.theaters);
const [activeIndex, setActiveIndex] = useState(0);
const [status, setStatus] = useState<{ kind: "ok" | "error"; text: string } | null>(
null,
);
const [saving, setSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [fileInputKey, setFileInputKey] = useState(0);
const [authState, setAuthState] = useState<"checking" | "ok" | "denied">(
"checking",
);
/* ตรวจสิทธิ์ด้วย POST /admin/session (loader อ่าน cookie ไม่ได้บนแพลตฟอร์มนี้) */
useEffect(() => {
let alive = true;
fetch("/admin/session", { method: "POST" })
.then((response) => response.json())
.then((result: { authenticated?: boolean }) => {
if (!alive) return;
if (result.authenticated) {
setAuthState("ok");
return;
}
setAuthState("denied");
window.location.replace("/admin/login?next=%2Fadmin");
})
.catch(() => {
if (alive) setAuthState("denied");
});
return () => {
alive = false;
};
}, []);
const active = list[activeIndex];
const jsonPreview = useMemo(() => JSON.stringify(list, null, 2), [list]);
const patchActive = (patch: Partial<Theater>) => {
setList((prev) =>
prev.map((item, index) =>
index === activeIndex ? { ...item, ...patch } : item,
),
);
setStatus(null);
};
const addTheater = () => {
const next = emptyTheater(`โรงหนังใหม่ ${list.length + 1}`);
setList((prev) => [...prev, next]);
setActiveIndex(list.length);
setStatus({ kind: "ok", text: "เพิ่มรายการใหม่ — กรอกข้อมูลแล้วกดบันทึก" });
};
const removeTheater = () => {
if (!active) return;
if (!window.confirm(`ลบ "${active.name}" ออกจากไฟล์ข้อมูล?`)) return;
const next = list.filter((_, index) => index !== activeIndex);
setList(next);
setActiveIndex(Math.max(0, Math.min(activeIndex, next.length - 1)));
setStatus({ kind: "ok", text: "ลบออกจากรายการแล้ว — กดบันทึกเพื่อเขียนลงไฟล์" });
};
const save = async () => {
setSaving(true);
try {
const response = await fetch(SAVE_ENDPOINT, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ theaters: list }),
});
const result = (await response.json()) as {
ok?: boolean;
message?: string;
saved?: number;
};
if (!response.ok || !result.ok) {
setStatus({
kind: "error",
text: result.message ?? `บันทึกไม่สำเร็จ (HTTP ${response.status})`,
});
return;
}
setStatus({ kind: "ok", text: result.message ?? "บันทึกแล้ว" });
revalidator.revalidate();
} catch (error) {
setStatus({
kind: "error",
text: error instanceof Error ? error.message : "บันทึกไม่สำเร็จ",
});
} finally {
setSaving(false);
}
};
const reload = () => {
setList(data.theaters);
setActiveIndex(0);
setStatus({ kind: "ok", text: "โหลดข้อมูลจากไฟล์ใหม่แล้ว" });
revalidator.revalidate();
};
/** อัปโหลดรูป (multipart) → เก็บไฟล์จริงใน public/images/theaters/ */
const uploadImage = async (file: File) => {
if (!active) return;
setUploading(true);
try {
const form = new FormData();
form.append("slug", active.slug);
form.append("image", file);
const response = await fetch("/admin/image", { method: "POST", body: form });
const result = (await response.json()) as {
ok?: boolean;
url?: string;
message?: string;
};
if (!response.ok || !result.ok || !result.url) {
setStatus({
kind: "error",
text: result.message ?? `อัปโหลดไม่สำเร็จ (HTTP ${response.status})`,
});
return;
}
// ลบไฟล์รูปเก่าทิ้ง (ถ้าเป็นไฟล์ที่เก็บในเว็บนี้)
if (active.image) {
await fetch("/admin/image?action=delete", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ url: active.image }),
});
}
patchActive({ image: result.url });
setStatus({
kind: "ok",
text: "อัปโหลดรูปแล้ว — กด \"บันทึก\" เพื่อเขียนลงไฟล์ JSON",
});
} catch (error) {
setStatus({
kind: "error",
text: error instanceof Error ? error.message : "อัปโหลดไม่สำเร็จ",
});
} finally {
setUploading(false);
setFileInputKey((key) => key + 1);
}
};
const removeImage = async () => {
if (!active) return;
const current = active.image;
patchActive({ image: null });
if (current) {
await fetch("/admin/image?action=delete", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ url: current }),
});
}
setStatus({ kind: "ok", text: "เอารูปออกแล้ว — กด \"บันทึก\" เพื่อยืนยัน" });
};
if (authState !== "ok") {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-3 bg-[#0D0D0D] text-center text-white">
<span className="font-['Jersey_15'] text-3xl text-[#8F0808]">
AlterFlixHub
</span>
<p className="text-sm text-[#B3B3B3]">
{authState === "checking"
? "กำลังตรวจสอบสิทธิ์…"
: "ไม่มีสิทธิ์เข้าถึง — กำลังพาไปหน้าล็อกอิน…"}
</p>
</div>
);
}
return (
<div className="min-h-screen w-full bg-[#0D0D0D] text-white">
<header className="sticky top-0 z-10 flex flex-wrap items-center justify-between gap-3 border-b border-[#222] bg-[#0D0D0D]/95 px-4 py-3 backdrop-blur md:px-8">
<div className="flex items-center gap-4">
<Link
to="/"
className="flex items-center gap-2 text-sm text-[#B3B3B3] transition hover:text-white"
>
<IconArrowLeft size={16} /> กลับหน้าบ้าน
</Link>
<span className="font-['Jersey_15'] text-2xl leading-none text-[#8F0808]">
AlterFlixHub
</span>
<span className="rounded-md border border-[#303030] px-2 py-1 text-xs text-[#B3B3B3]">
ระบบหลังบ้าน
</span>
</div>
<div className="flex items-center gap-2">
<span className="hidden text-xs text-[#666] sm:block">
ไฟล์: public/data/theaters.json · แก้ล่าสุด{" "}
{new Date(data.updatedAt).toLocaleString("th-TH")}
</span>
<button
onClick={reload}
className="flex items-center gap-2 rounded-lg border border-[#303030] px-3 py-2 text-sm text-[#B3B3B3] transition hover:border-[#A92626] hover:text-white"
>
<IconRefresh size={16} /> โหลดใหม่
</button>
<button
onClick={save}
disabled={saving}
className="flex items-center gap-2 rounded-lg bg-[#8F0808] px-4 py-2 text-sm font-medium transition hover:bg-[#a30a0a] disabled:opacity-50"
>
<IconDeviceFloppy size={16} />
{saving ? "กำลังบันทึก…" : "บันทึก"}
</button>
<Form method="post" action="/admin/logout">
<button
type="submit"
className="flex items-center gap-2 rounded-lg border border-[#303030] px-3 py-2 text-sm text-[#B3B3B3] transition hover:border-[#A92626] hover:text-white"
>
<IconLogout size={16} /> ออกจากระบบ
</button>
</Form>
</div>
</header>
{status ? (
<div
className={`px-4 py-2 text-sm md:px-8 ${
status.kind === "ok"
? "bg-[#0f2d17] text-[#7ee2a8]"
: "bg-[#3a1113] text-[#ff9a9a]"
}`}
>
{status.text}
</div>
) : null}
<div className="mx-auto grid max-w-[1440px] gap-4 px-4 py-4 md:px-8 lg:grid-cols-[320px_minmax(0,1fr)]">
{/* ---------- รายการโรง ---------- */}
<aside className="flex flex-col gap-3">
<div className="flex items-center justify-between">
<h1 className="text-lg font-semibold">
โรงหนัง ({list.length})
</h1>
<button
onClick={addTheater}
className="flex items-center gap-1 rounded-lg border border-[#303030] px-2 py-1.5 text-xs text-[#B3B3B3] transition hover:border-[#A92626] hover:text-white"
>
<IconPlus size={14} /> เพิ่ม
</button>
</div>
<div className="flex max-h-[70vh] flex-col gap-1 overflow-y-auto pr-1">
{list.map((theater, index) => (
<div
key={`${theater.slug}-${index}`}
className={`flex items-stretch gap-1 rounded-lg border transition ${
index === activeIndex
? "border-[#A92626] bg-[#1B1B1B]"
: "border-[#222] bg-[#111] hover:border-[#3a3a3a]"
}`}
>
<button
onClick={() => setActiveIndex(index)}
className="flex flex-1 flex-col items-start gap-0.5 px-3 py-2 text-left"
>
<span className="flex items-center gap-1.5 text-sm font-medium">
{theater.name || "(ไม่มีชื่อ)"}
{theater.hidden ? (
<span className="rounded border border-[#5a3a00] bg-[#2a1f00] px-1 py-0.5 text-[10px] text-[#e0b357]">
ซ่อน
</span>
) : null}
</span>
<span className="text-[11px] text-[#777]">
/{theater.slug}
</span>
<span className="text-[11px] text-[#666]">
{theater.categories.join(" · ") || "ไม่มีหมวด"}
</span>
</button>
<button
onClick={() =>
setList((prev) =>
prev.map((item, i) =>
i === index ? { ...item, hidden: !item.hidden } : item,
),
)
}
aria-label={
theater.hidden ? "แสดงบนหน้าแรก" : "ซ่อนจากหน้าแรก"
}
title={theater.hidden ? "แสดงบนหน้าแรก" : "ซ่อนจากหน้าแรก"}
className={`flex w-9 items-center justify-center rounded-r-lg ${
theater.hidden
? "text-[#e0b357] hover:bg-[#2a1f00]"
: "text-[#666] hover:bg-[#1f1f1f] hover:text-white"
}`}
>
{theater.hidden ? (
<IconEyeOff size={16} />
) : (
<IconEye size={16} />
)}
</button>
</div>
))}
{list.length === 0 ? (
<p className="rounded-lg border border-dashed border-[#2a2a2a] px-3 py-6 text-center text-xs text-[#777]">
ยังไม่มีข้อมูล — กด "เพิ่ม" เพื่อเริ่ม
</p>
) : null}
</div>
</aside>
{/* ---------- ฟอร์มแก้ไข ---------- */}
<main className="flex flex-col gap-4">
{active ? (
<>
<section className={`${panelClass} grid gap-3 sm:grid-cols-2`}>
<Field
label="ชื่อโรงหนัง"
value={active.name}
onChange={(name) => patchActive({ name })}
/>
<div className="flex flex-col gap-1">
<Field
label="slug (ใช้ใน URL)"
value={active.slug}
onChange={(slug) => patchActive({ slug: toSlug(slug) })}
/>
<span className="text-[11px] text-[#666]">
/cinema/{active.slug || "…"}
</span>
</div>
<Field
label="พื้นที่ / ชั้น"
value={active.area}
onChange={(area) => patchActive({ area })}
/>
<Field
label="ระยะทาง"
value={active.distance}
onChange={(distance) => patchActive({ distance })}
/>
<CsvField
label="หมวดหนัง (คั่นด้วยจุลภาค)"
values={active.categories}
onChange={(categories) => patchActive({ categories })}
/>
<div className="flex flex-wrap gap-1 self-end">
{CATEGORY_OPTIONS.map((option) => {
const on = active.categories.includes(option);
return (
<button
key={option}
onClick={() =>
patchActive({
categories: on
? active.categories.filter((c) => c !== option)
: [...active.categories, option],
})
}
className={`rounded-full border px-2 py-1 text-[11px] transition ${
on
? "border-[#A92626] text-[#D47272]"
: "border-[#2f2f2f] text-[#888] hover:border-[#555]"
}`}
>
{option}
</button>
);
})}
</div>
<Field
label="Google Map URL"
value={active.map_url ?? ""}
onChange={(map_url) => patchActive({ map_url: map_url || null })}
/>
<Field
label="ช่องทางชำระเงิน (คั่นด้วยจุลภาค)"
value={active.payments.join(", ")}
onChange={(text) =>
patchActive({
payments: text
.split(",")
.map((part) => part.trim())
.filter(Boolean),
})
}
/>
<div className="sm:col-span-2">
<Area
label="คำอธิบาย"
value={active.description ?? ""}
onChange={(description) =>
patchActive({ description: description || null })
}
rows={3}
/>
</div>
<div className="sm:col-span-2">
<Area
label="ที่อยู่"
value={active.address ?? ""}
onChange={(address) => patchActive({ address: address || null })}
rows={2}
/>
</div>
</section>
<section className={`${panelClass} flex flex-col gap-3`}>
<div className="flex flex-wrap items-center justify-between gap-2">
<h2 className="text-sm font-semibold">รูปโรงหนัง</h2>
<span className="text-[11px] text-[#888]">
JPG / PNG / WebP / AVIF · ไม่เกิน 6 MB
</span>
</div>
<div className="flex flex-col gap-4 sm:flex-row">
<div className="relative h-[210px] w-[158px] shrink-0 overflow-hidden rounded-xl border border-[#2a2a2a] bg-gradient-to-br from-[#3a2a22] via-[#2a2a3a] to-[#1b1b1b]">
{active.image ? (
<img
src={active.image}
alt={`รูปโรงหนัง ${active.name}`}
loading="lazy"
className="h-full w-full object-cover"
/>
) : (
<span className="absolute inset-0 flex items-center justify-center px-2 text-center text-[11px] leading-relaxed text-[#999]">
ยังไม่มีรูป
<br />
ใช้พื้นหลังไล่สีแทน
</span>
)}
</div>
<div className="flex flex-1 flex-col gap-2">
<label className="flex flex-col gap-1">
<span className={labelClass}>อัปโหลดรูปใหม่</span>
<input
key={fileInputKey}
type="file"
accept=".jpg,.jpeg,.png,.webp,.avif,image/jpeg,image/png,image/webp,image/avif"
disabled={uploading}
onChange={(event) => {
const file = event.target.files?.[0];
if (file) void uploadImage(file);
}}
className="w-full cursor-pointer rounded-lg border border-dashed border-[#3a3a3a] bg-[#161616] px-3 py-2 text-xs text-[#B3B3B3] file:mr-3 file:cursor-pointer file:rounded file:border-0 file:bg-[#8F0808] file:px-3 file:py-1.5 file:text-xs file:text-white hover:border-[#A92626]"
/>
</label>
{uploading ? (
<p className="text-xs text-[#e0b357]">กำลังอัปโหลดรูป…</p>
) : null}
<Field
label="หรือใส่ URL รูปเอง"
value={active.image ?? ""}
placeholder="/images/theaters/... หรือ https://..."
onChange={(image) => patchActive({ image: image || null })}
/>
<div className="flex flex-wrap gap-2">
<button
onClick={removeImage}
disabled={!active.image}
className="flex items-center gap-2 rounded-lg border border-[#3a1113] px-3 py-2 text-sm text-[#ff9a9a] transition hover:bg-[#3a1113] disabled:cursor-not-allowed disabled:opacity-40"
>
<IconTrash size={14} /> เอารูปออก
</button>
<span className="self-center text-[11px] text-[#666]">
รูปจะถูกใช้ทั้งการ์ดหน้าแรกและรูปใหญ่หน้ารายละเอียด
</span>
</div>
</div>
</div>
</section>
<section className={`${panelClass} flex flex-col gap-3`}>
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold">การเดินทาง</h2>
<button
onClick={() =>
patchActive({
transport: [
...active.transport,
{ icon: "bus", label: "", value: "" },
],
})
}
className="flex items-center gap-1 text-xs text-[#B3B3B3] hover:text-white"
>
<IconPlus size={14} /> เพิ่มช่องทาง
</button>
</div>
{active.transport.map((row, index) => (
<div key={index} className="grid gap-2 sm:grid-cols-[120px_1fr_1fr_32px]">
<select
className={inputClass}
value={row.icon}
onChange={(event) => {
const transport = [...active.transport];
transport[index] = { ...row, icon: event.target.value };
patchActive({ transport });
}}
>
{ICON_NAMES.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
<input
className={inputClass}
placeholder="ชื่อช่องทาง"
value={row.label}
onChange={(event) => {
const transport: TheaterTransport[] = [...active.transport];
transport[index] = { ...row, label: event.target.value };
patchActive({ transport });
}}
/>
<input
className={inputClass}
placeholder="รายละเอียด"
value={row.value}
onChange={(event) => {
const transport: TheaterTransport[] = [...active.transport];
transport[index] = { ...row, value: event.target.value };
patchActive({ transport });
}}
/>
<button
aria-label="ลบช่องทาง"
onClick={() =>
patchActive({
transport: active.transport.filter((_, i) => i !== index),
})
}
className="flex items-center justify-center rounded-lg border border-[#2f2f2f] text-[#888] hover:border-[#A92626] hover:text-[#ff9a9a]"
>
<IconTrash size={14} />
</button>
</div>
))}
{active.transport.length === 0 ? (
<p className="text-xs text-[#666]">ยังไม่มีข้อมูลการเดินทาง</p>
) : null}
</section>
<section className={`${panelClass} flex flex-col gap-3`}>
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold">ช่องทางติดต่อ</h2>
<button
onClick={() =>
patchActive({
contacts: [...active.contacts, { label: "", value: "" }],
})
}
className="flex items-center gap-1 text-xs text-[#B3B3B3] hover:text-white"
>
<IconPlus size={14} /> เพิ่มช่องทาง
</button>
</div>
{active.contacts.map((row, index) => (
<div key={index} className="grid gap-2 sm:grid-cols-[1fr_1fr_32px]">
<input
className={inputClass}
placeholder="ชื่อช่องทาง"
value={row.label}
onChange={(event) => {
const contacts: TheaterContact[] = [...active.contacts];
contacts[index] = { ...row, label: event.target.value };
patchActive({ contacts });
}}
/>
<input
className={inputClass}
placeholder="ค่า"
value={row.value}
onChange={(event) => {
const contacts: TheaterContact[] = [...active.contacts];
contacts[index] = { ...row, value: event.target.value };
patchActive({ contacts });
}}
/>
<button
aria-label="ลบช่องทางติดต่อ"
onClick={() =>
patchActive({
contacts: active.contacts.filter((_, i) => i !== index),
})
}
className="flex items-center justify-center rounded-lg border border-[#2f2f2f] text-[#888] hover:border-[#A92626] hover:text-[#ff9a9a]"
>
<IconTrash size={14} />
</button>
</div>
))}
{active.contacts.length === 0 ? (
<p className="text-xs text-[#666]">ยังไม่มีข้อมูลติดต่อ</p>
) : null}
</section>
<section className={`${panelClass} flex flex-col gap-3`}>
<div className="flex items-center justify-between">
<h2 className="text-sm font-semibold">สิ่งอำนวยความสะดวก</h2>
<button
onClick={() =>
patchActive({
facilities: [
...active.facilities,
{ icon: "sofa", title: "", sub: "" },
],
})
}
className="flex items-center gap-1 text-xs text-[#B3B3B3] hover:text-white"
>
<IconPlus size={14} /> เพิ่มรายการ
</button>
</div>
{active.facilities.map((row, index) => (
<div key={index} className="grid gap-2 sm:grid-cols-[120px_1fr_1fr_32px]">
<select
className={inputClass}
value={row.icon}
onChange={(event) => {
const facilities: TheaterFacility[] = [...active.facilities];
facilities[index] = { ...row, icon: event.target.value };
patchActive({ facilities });
}}
>
{ICON_NAMES.map((name) => (
<option key={name} value={name}>
{name}
</option>
))}
</select>
<input
className={inputClass}
placeholder="ชื่อ"
value={row.title}
onChange={(event) => {
const facilities: TheaterFacility[] = [...active.facilities];
facilities[index] = { ...row, title: event.target.value };
patchActive({ facilities });
}}
/>
<input
className={inputClass}
placeholder="รายละเอียด"
value={row.sub}
onChange={(event) => {
const facilities: TheaterFacility[] = [...active.facilities];
facilities[index] = { ...row, sub: event.target.value };
patchActive({ facilities });
}}
/>
<button
aria-label="ลบรายการ"
onClick={() =>
patchActive({
facilities: active.facilities.filter((_, i) => i !== index),
})
}
className="flex items-center justify-center rounded-lg border border-[#2f2f2f] text-[#888] hover:border-[#A92626] hover:text-[#ff9a9a]"
>
<IconTrash size={14} />
</button>
</div>
))}
{active.facilities.length === 0 ? (
<p className="text-xs text-[#666]">ยังไม่มีข้อมูลสิ่งอำนวยความสะดวก</p>
) : null}
</section>
<section className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-[#2A2A2A] bg-[#111] p-4">
<div className="flex flex-col gap-1">
<Link
to={`/cinema/${active.slug}`}
className="text-sm text-[#B3B3B3] underline decoration-[#444] transition hover:text-white"
>
ดูหน้ารายละเอียดของโรงนี้ →
</Link>
<span className="text-[11px] text-[#666]">
{active.hidden
? "สถานะ: ซ่อนจากหน้าแรก (เปิดด้วยลิงก์ตรงได้)"
: "สถานะ: แสดงบนหน้าแรก"}
</span>
</div>
<div className="flex flex-wrap items-center gap-2">
<button
onClick={() => patchActive({ hidden: !active.hidden })}
className={`flex items-center gap-2 rounded-lg border px-3 py-2 text-sm transition ${
active.hidden
? "border-[#5a3a00] text-[#e0b357] hover:bg-[#2a1f00]"
: "border-[#303030] text-[#B3B3B3] hover:border-[#555] hover:text-white"
}`}
>
{active.hidden ? (
<>
<IconEye size={16} /> แสดงบนหน้าแรก
</>
) : (
<>
<IconEyeOff size={16} /> ซ่อนจากหน้าแรก
</>
)}
</button>
<button
onClick={removeTheater}
className="flex items-center gap-2 rounded-lg border border-[#3a1113] px-3 py-2 text-sm text-[#ff9a9a] transition hover:bg-[#3a1113]"
>
<IconTrash size={16} /> ลบโรงนี้
</button>
</div>
</section>
<details className="rounded-xl border border-[#2A2A2A] bg-[#111] p-4">
<summary className="cursor-pointer text-sm font-semibold">
ดู JSON ที่จะบันทึก
</summary>
<pre className="mt-3 max-h-[360px] overflow-auto rounded-lg bg-[#0a0a0a] p-3 text-[11px] leading-relaxed text-[#9fd3a8]">
{jsonPreview}
</pre>
</details>
</>
) : (
<p className={panelClass}>ยังไม่มีข้อมูล — กด "เพิ่ม" ที่แถบซ้าย</p>
)}
</main>
</div>
</div>
);
}
+358 -16
View File
@@ -1,21 +1,363 @@
import { Navigate, useParams } from "react-router";
import {
IconArrowBackUp,
IconBrandFacebook,
IconBrandInstagram,
IconBrandLinkedin,
IconBrandTelegram,
IconBrandYoutube,
IconBus,
IconChevronDown,
IconChevronLeft,
IconChevronRight,
IconCircleCheck,
IconExternalLink,
IconMap,
IconMapPin,
} from "@tabler/icons-react";
import { Link, useLoaderData, useParams } from "react-router";
/**
* เส้นทางเดิม /cinema/:slug → หน้าเดียว /?cinema=<slug>
* ------------------------------------------------------------
* ★ ใช้ <Navigate> (client-side) → ไม่รีเฟรชหน้า ไม่โหลดใหม่
* ★ เก็บไว้เพื่อให้ลิงก์เก่า/ลิงก์ที่แชร์ไว้แล้วยังใช้ได้
*/
export default function CinemaRedirect() {
const { slug } = useParams();
import type { Theater } from "@/lib/theaters";
import { getTheater, resolveIcon } from "@/lib/theaters";
import { readTheatersFile } from "@/lib/theaters-store.server";
export async function loader() {
const file = await readTheatersFile();
return { theaters: file.theaters, updatedAt: file.updated_at };
}
export function meta() {
return [{ title: "รายละเอียดโรงหนัง — AlterFlixHub" }];
}
const BRAND = "#8F0808";
const BORDER = "#332B2B";
const socials = [
IconBrandFacebook,
IconBrandInstagram,
IconBrandLinkedin,
IconBrandYoutube,
IconBrandTelegram,
];
function Logo() {
return (
<Navigate
to={{
pathname: "/",
search: slug ? `?cinema=${encodeURIComponent(slug)}` : "",
}}
replace
/>
<Link to="/" aria-label="AlterFlixHub">
<span
className="text-4xl leading-none"
style={{ fontFamily: "'Jersey 15', sans-serif", color: BRAND }}
>
AlterFlixHub
</span>
</Link>
);
}
function NotFound() {
return (
<div className="flex min-h-screen flex-col items-center justify-center gap-6 bg-[#0D0D0D] px-6 text-center text-white">
<h1 className="text-3xl font-bold">ไม่พบโรงหนังที่ค้นหา</h1>
<p className="text-sm text-[#999]">
ลิงก์อาจเปลี่ยนไปแล้ว หรือโรงนี้ยังไม่มีในระบบ
</p>
<Link
to="/"
className="flex items-center gap-2 rounded-lg px-5 py-3"
style={{ background: BRAND }}
>
<IconArrowBackUp size={20} /> กลับไปหน้ารายชื่อโรงหนัง
</Link>
</div>
);
}
/**
* หน้ารายละเอียดโรงหนัง — /cinema/:slug
* ★ อ่านข้อมูลจากไฟล์ JSON ผ่าน loader
* ★ "ย้อนกลับ" = <Link to="/"> , "โรงหนังอิสระอื่นๆ" ลิงก์ไปโรงอื่น
*/
export default function CinemaDetailRoute() {
const { theaters } = useLoaderData() as {
theaters: Theater[];
updatedAt: string;
};
const slug = useParams().slug;
const theater = getTheater(theaters, slug);
if (!theater) return <NotFound />;
const others = theaters.filter((item) => item.slug !== theater.slug).slice(0, 3);
return (
<div className="relative min-h-screen overflow-hidden bg-[#0D0D0D] text-white">
<div
className="pointer-events-none absolute left-1/2 top-[649px] size-[382px] -translate-x-1/2 rounded-full opacity-[0.66] blur-[237px]"
style={{ background: "#4C0404" }}
/>
<header className="relative flex items-center justify-between px-4 py-4 md:px-[108px]">
<Logo />
<div className="flex items-center gap-2">
<div className="h-4 w-[21px] overflow-hidden">
<div className="h-[2.75px] bg-[#A51931]" />
<div className="mt-[2.67px] h-[5.33px] bg-[#2D2A4A]" />
<div className="mt-[2.66px] h-[2.67px] bg-[#A51931]" />
</div>
<span className="text-lg font-medium">TH</span>
<IconChevronDown size={16} />
</div>
</header>
<main className="relative mx-auto flex w-full max-w-[1440px] flex-col gap-10 px-4 pb-16 pt-4 md:px-[108px] md:pt-6">
<Link
to="/"
className="inline-flex w-fit items-center gap-2 text-xl font-medium transition hover:text-[#D47272]"
>
<IconArrowBackUp size={24} />
ย้อนกลับ
</Link>
<section className="grid gap-6 lg:grid-cols-[minmax(0,807px)_minmax(0,387px)]">
<div className="relative aspect-[269/202] w-full overflow-hidden rounded-xl bg-gradient-to-br from-[#3a2a22] via-[#2a2a3a] to-[#1b1b1b] lg:aspect-auto lg:h-[606px]">
{theater.image ? (
<img
src={theater.image}
alt={`รูปโรงหนัง ${theater.name}`}
className="absolute inset-0 h-full w-full object-cover"
/>
) : null}
<button
aria-label="รูปก่อนหน้า"
className="absolute left-6 top-1/2 flex size-10 -translate-y-1/2 items-center justify-center rounded-full bg-black/50"
>
<IconChevronLeft size={24} />
</button>
<button
aria-label="รูปถัดไป"
className="absolute right-6 top-1/2 flex size-10 -translate-y-1/2 items-center justify-center rounded-full bg-black/50"
>
<IconChevronRight size={24} />
</button>
</div>
<div className="grid grid-cols-2 gap-6 lg:grid-cols-1 lg:grid-rows-2">
<div className="aspect-[387/290] rounded-xl bg-gradient-to-br from-[#2a2a3a] via-[#1f2a3a] to-[#1b1b1b]" />
<div className="relative aspect-[387/290] overflow-hidden rounded-xl bg-gradient-to-br from-[#3a3a4a] via-[#2a2a2a] to-[#1b1b1b]">
<div className="absolute bottom-2.5 right-2.5 flex size-[60px] items-center justify-center rounded-lg bg-black/80 text-lg font-medium">
5+
</div>
</div>
</div>
</section>
<section className="grid gap-10 lg:grid-cols-[minmax(0,749px)_minmax(0,384px)] lg:justify-between">
<div className="flex flex-col gap-12">
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-4">
<div className="flex flex-wrap gap-2">
{theater.categories.map((t) => (
<span
key={t}
className="rounded-[18px] border border-[#A92626] px-4 py-2 text-sm text-[#D47272]"
style={{
background:
"linear-gradient(180deg, rgba(143,8,8,0.3) 0%, rgba(27,27,27,0) 100%)",
}}
>
{t}
</span>
))}
</div>
<h1 className="text-[40px] font-bold leading-[1.3]">
{theater.name}
</h1>
{theater.hidden ? (
<span className="w-fit rounded border border-[#5a3a00] bg-[#2a1f00] px-2 py-1 text-xs text-[#e0b357]">
ซ่อนจากหน้าแรก
</span>
) : null}
</div>
<div className="flex flex-wrap items-center justify-between gap-4">
<div className="flex items-center gap-2 text-lg">
<IconMapPin size={24} className="shrink-0" />
{theater.area}
</div>
{theater.map_url ? (
<a
href={theater.map_url}
target="_blank"
rel="noreferrer"
className="flex w-[200px] items-center justify-center gap-2 rounded-lg border border-white px-4 py-2 text-lg font-medium transition hover:bg-white/10"
>
เปิด Google map
<IconMap size={24} />
</a>
) : null}
</div>
<p className="text-xl leading-[1.3]">
{theater.description ??
"ยังไม่มีข้อมูลรายละเอียดของโรงหนังนี้ — อยู่ระหว่างรวบรวมข้อมูล"}
</p>
</div>
{theater.transport.length > 0 ? (
<div className="flex flex-col">
{theater.transport.map((r, i) => {
const Icon = resolveIcon(r.icon) ?? IconBus;
return (
<div
key={r.label}
className="flex flex-col justify-between gap-1 py-2.5 sm:min-h-10 sm:flex-row sm:gap-4"
style={{
borderBottom:
i < theater.transport.length - 1
? `1px solid ${BORDER}`
: undefined,
}}
>
<div className="flex items-center gap-2 font-medium">
<Icon size={20} />
{r.label}
</div>
<div className="sm:text-right">{r.value}</div>
</div>
);
})}
</div>
) : null}
</div>
<aside
className="flex flex-col justify-between gap-6 rounded-xl p-6"
style={{ border: `1px solid ${BORDER}` }}
>
<div className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold leading-[1.3]">
สอบถามข้อมูลและจองตั๋ว
</h2>
{theater.contacts.length > 0 ? (
theater.contacts.map((c) => (
<div key={c.label} className="flex flex-col gap-2">
<span className="text-sm text-[#999]">{c.label}</span>
<div className="flex items-center justify-between">
<span>{c.value}</span>
<IconExternalLink size={16} />
</div>
</div>
))
) : (
<p className="text-sm text-[#999]">
ยังไม่มีช่องทางติดต่อของโรงนี้
</p>
)}
{theater.payments.length > 0 ? (
<div className="flex flex-col gap-3">
<span className="text-sm text-[#999]">Payment</span>
<div className="flex flex-wrap items-center gap-6">
{theater.payments.map((p) => (
<span key={p} className="flex items-center gap-1 text-sm">
<IconCircleCheck size={16} />
{p}
</span>
))}
</div>
</div>
) : null}
</div>
<button
className="flex h-12 items-center justify-center gap-2 rounded-lg px-4 transition hover:bg-[#a30a0a]"
style={{ background: BRAND, border: `1px solid ${BRAND}` }}
>
ดูรอบฉาย
</button>
</aside>
</section>
<section className="grid gap-10 lg:grid-cols-[minmax(0,749px)_minmax(0,384px)] lg:justify-between">
<div className="flex flex-col gap-8">
<h2 className="text-2xl font-semibold leading-[1.3]">
สิ่งอำนวยความสะดวก
</h2>
{theater.facilities.length > 0 ? (
<div className="grid grid-cols-2 gap-x-4 gap-y-10 sm:grid-cols-4">
{theater.facilities.map((f) => {
const Icon = resolveIcon(f.icon);
return (
<div
key={f.title}
className="flex flex-col items-center gap-3"
>
<div
className="flex size-[72px] items-center justify-center rounded-full"
style={{ background: "rgba(143,8,8,0.4)" }}
>
{Icon ? <Icon size={40} stroke={1.5} /> : null}
</div>
<div className="text-center">
<div className="font-medium">{f.title}</div>
<div className="mt-1 text-sm text-[#B3B3B3]">{f.sub}</div>
</div>
</div>
);
})}
</div>
) : (
<p className="text-sm text-[#999]">
ยังไม่มีข้อมูลสิ่งอำนวยความสะดวก
</p>
)}
</div>
<aside
className="flex flex-col gap-6 self-start rounded-xl p-6"
style={{ border: `1px solid ${BORDER}` }}
>
<div className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold leading-[1.3]">ที่ตั้ง</h2>
<div className="h-[183px] rounded-xl bg-[#E8E8E8]" />
</div>
<p className="text-sm leading-[1.3] text-[#999]">
{theater.address ?? theater.area}
</p>
</aside>
</section>
<section className="flex flex-col gap-8">
<h2 className="text-2xl font-semibold leading-[1.3]">
โรงหนังอิสระอื่นๆ
</h2>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3">
{others.map((other) => (
<Link
key={other.slug}
to={`/cinema/${other.slug}`}
className="flex h-[180px] flex-col justify-end rounded-[20px] bg-gradient-to-br from-[#3a2a22] via-[#2a2a3a] to-[#1b1b1b] p-2 transition hover:from-[#4a3320]"
>
<div className="flex flex-col gap-1.5 rounded-2xl border border-white/10 bg-[#1B1B1B]/80 p-3 backdrop-blur-xl">
<h3 className="text-sm font-semibold">{other.name}</h3>
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
<IconMapPin size={12} /> {other.area}
</p>
</div>
</Link>
))}
</div>
</section>
</main>
<footer className="relative flex flex-col items-center gap-10 px-4 py-10 md:px-[108px]">
<Logo />
<div className="flex gap-8">
{socials.map((I, i) => (
<I key={i} size={42} stroke={1.25} />
))}
</div>
<div className="flex w-full max-w-[1218px] flex-col items-center gap-8">
<div className="h-px w-full bg-white/20" />
<p className="text-sm">Copyright © AlterFlixHub</p>
</div>
</footer>
</div>
);
}
+115
View File
@@ -0,0 +1,115 @@
import { useEffect } from "react";
import { useSearchParams } from "react-router";
import { CINEMAS, getCinema } from "@/lib/cinemas";
import { useLang } from "@/lib/i18n";
import { CinemaCard } from "@/components/cinema/CinemaCard";
import { CinemaDetailSheet } from "@/components/cinema/CinemaDetailSheet";
import { SiteFooter, SiteHeader } from "@/components/cinema/SiteHeader";
export function meta() {
return [
{ title: "AlterFlixHub — โรงภาพยนตร์" },
{
name: "description",
content: "เลือกโรงภาพยนตร์ที่ใช่ ดูรอบฉายและรายละเอียดได้ในที่เดียว",
},
];
}
/**
* หน้าแรก (Home) — รายการโรงภาพยนตร์ + รายละเอียดในหน้าเดียวกัน
* ------------------------------------------------------------
* ★ เว็บหน้าเดียว: การ์ด → เปิด sheet ทับ ไม่เปลี่ยน route, ไม่รีเฟรช
* รายการด้านหลังไม่ unmount → scroll ที่เลื่อนไว้ยังอยู่
* ★ URL = /?cinema=<slug> (pushState) → แชร์ลิงก์ได้, back ปิด sheet
* ★ มือถือ 6" (360–430px): การ์ด 1 คอลัมน์แนวนอน, sheet เต็มจอ
* ★ แท็บเล็ต (640–1023px): 2 คอลัมน์
* ★ เดสก์ท็อป (≥1024px): 3 คอลัมน์, sheet กลางจอ
*/
export default function HomeRoute() {
const { t } = useLang();
const [searchParams, setSearchParams] = useSearchParams();
const activeSlug = searchParams.get("cinema");
const activeCinema = getCinema(activeSlug ?? undefined);
/** เปิดรายละเอียด — push history entry (ปุ่ม back ของเบราว์เซอร์จะปิด sheet) */
const openCinema = (slug: string) => {
setSearchParams({ cinema: slug });
};
/** ปิด — replace เพื่อไม่ให้ history บวมด้วย entry ของ state "ปิด" */
const closeCinema = () => {
setSearchParams({}, { replace: true });
};
/* title เปลี่ยนตามโรงที่เปิด — ลิงก์ที่แชร์จะได้ชื่อถูก */
useEffect(() => {
document.title = activeCinema
? `${activeCinema.name} — AlterFlixHub`
: "AlterFlixHub — โรงภาพยนตร์";
}, [activeCinema]);
return (
<div className="relative min-h-full bg-gradient-to-b from-[#0a0a0a] via-[#160505] to-[#0a0a0a] text-white">
{/* แสงแดงเรือง ๆ หลัง hero — decorative */}
<div
className="pointer-events-none absolute left-1/2 top-20 h-56 w-56 -translate-x-1/2 rounded-full opacity-50 blur-[110px] sm:top-28 sm:h-80 sm:w-80 sm:blur-[140px]"
style={{ background: "#4C0404" }}
aria-hidden="true"
/>
<SiteHeader />
<main className="relative mx-auto w-full max-w-[1160px] px-4 pb-10 sm:px-5 sm:pb-14">
{/* ---------- Hero ---------- */}
<section className="py-8 text-center sm:py-12 lg:py-16">
<h1 className="mx-auto max-w-[22ch] text-[28px] font-black leading-[1.2] tracking-tight sm:text-[38px] lg:text-[48px]">
<span
className="bg-clip-text text-transparent"
style={{
backgroundImage:
"linear-gradient(135deg,#ff1f1f 0%,#e00000 45%,#7a0000 100%)",
}}
>
{t("home.hero1")}
</span>
<br />
{t("home.hero2")}
</h1>
<p className="mx-auto mt-3 max-w-[40ch] text-sm leading-relaxed text-[#9ca3af] sm:mt-4 sm:max-w-[52ch] sm:text-base">
{t("home.lead")}
</p>
</section>
{/* ---------- รายการโรงภาพยนตร์ ---------- */}
<section aria-labelledby="cinemas-heading">
<div className="mb-3 flex items-baseline gap-2 sm:mb-4">
<h2 id="cinemas-heading" className="text-lg font-extrabold sm:text-xl">
{t("home.sectionTitle")}
</h2>
<span className="text-xs text-[#9ca3af] sm:text-sm">
{t("home.count", { n: CINEMAS.length })}
</span>
</div>
{/* มือถือ = 1 คอลัมน์ · แท็บเล็ต = 2 · เดสก์ท็อป = 3 */}
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 sm:gap-4 lg:grid-cols-3">
{CINEMAS.map((cinema) => (
<CinemaCard key={cinema.slug} cinema={cinema} onSelect={openCinema} />
))}
</div>
</section>
</main>
<SiteFooter />
{/* ---------- รายละเอียด (overlay บนหน้าเดิม) ---------- */}
<CinemaDetailSheet
slug={activeCinema ? activeCinema.slug : null}
onClose={closeCinema}
onSelectCinema={openCinema}
/>
</div>
);
}
+192
View File
@@ -0,0 +1,192 @@
{
"updated_at": "2026-10-27T15:19:41.647Z",
"theaters": [
{
"slug": "house-cinema-samyan",
"name": "HOUSE CINEMA SAMYAN",
"area": "ชั้น 5 สามย่านมิตรทาวน์ กรุงเทพฯ",
"distance": "0 km.",
"categories": [
"หนังนอกกระแส"
],
"description": "โรงภาพยนตร์สำหรับคนที่อยากค้นพบหนังหลากหลาย เน้นภาพยนตร์นอกกระแสและเรื่องที่ไม่ได้เข้าฉายในวงกว้าง พร้อมเรื่องราวและมุมมองที่แตกต่างสำหรับคนรักหนัง",
"address": "ชั้น 5 ศูนย์การค้าสามย่านมิตรทาวน์ 944/1 ถนนพระราม 4 แขวงวังใหม่ เขตปทุมวัน กรุงเทพฯ 10330",
"map_url": "https://maps.google.com/?q=House+Samyan",
"transport": [
{
"icon": "car",
"label": "รถยนต์ส่วนตัว",
"value": "ที่จอดรถภายในศูนย์การค้าสามย่านมิตรทาวน์"
},
{
"icon": "train",
"label": "รถไฟฟ้า",
"value": "MRT สถานีสามย่าน"
},
{
"icon": "bus",
"label": "รถประจำทาง",
"value": "29, 34, 36, 40, 47, 50"
}
],
"contacts": [
{
"label": "Website",
"value": "www.housesamyan.com"
},
{
"label": "Mobile Application",
"value": "House Cinema"
},
{
"label": "Facebook",
"value": "House Samyan"
},
{
"label": "Call",
"value": "098-869-0997"
}
],
"payments": [
"เงินสด",
"บัตรเครดิต",
"สแกนจ่าย"
],
"facilities": [
{
"icon": "sofa",
"title": "โซนนั่งรอ",
"sub": "บริเวณโถงโรงภาพยนตร์"
},
{
"icon": "ticket",
"title": "จุดจำหน่ายตั๋ว",
"sub": "Box Office ชั้น 5"
},
{
"icon": "food",
"title": "ร้านอาหาร",
"sub": "ภายในศูนย์การค้า"
},
{
"icon": "cafe",
"title": "ร้านคาเฟ่",
"sub": "บริเวณโถงโรงภาพยนตร์"
},
{
"icon": "garden",
"title": "สวนหย่อม",
"sub": "ลานกลางแจ้ง"
},
{
"icon": "book",
"title": "ร้านหนังสือ",
"sub": "ภายในศูนย์การค้า"
},
{
"icon": "workspace",
"title": "Co-Learning Space",
"sub": "บริเวณโถงโรงภาพยนตร์"
},
{
"icon": "shop",
"title": "อื่นๆ",
"sub": "ร้านทำผม ร้านทำเล็บ"
}
],
"hidden": false,
"image": null
},
{
"slug": "major-hollywood",
"name": "MAJOR HOLLYWOOD",
"area": "กรุงเทพฯ",
"distance": "—",
"categories": [
"หนังในกระแส"
],
"description": null,
"address": null,
"map_url": null,
"transport": [],
"contacts": [],
"payments": [],
"facilities": [],
"hidden": false,
"image": null
},
{
"slug": "century",
"name": "CENTURY",
"area": "กรุงเทพฯ",
"distance": "—",
"categories": [
"หนังในกระแส"
],
"description": null,
"address": null,
"map_url": null,
"transport": [],
"contacts": [],
"payments": [],
"facilities": [],
"hidden": false,
"image": null
},
{
"slug": "ck-plaza",
"name": "CK PLAZA",
"area": "กรุงเทพฯ",
"distance": "—",
"categories": [
"หนังในกระแส"
],
"description": null,
"address": null,
"map_url": null,
"transport": [],
"contacts": [],
"payments": [],
"facilities": [],
"hidden": false,
"image": null
},
{
"slug": "thana-cineplex",
"name": "THANA CINEPLEX",
"area": "กรุงเทพฯ",
"distance": "—",
"categories": [
"หนังในกระแส"
],
"description": null,
"address": null,
"map_url": null,
"transport": [],
"contacts": [],
"payments": [],
"facilities": [],
"hidden": false,
"image": null
},
{
"slug": "coliseum-paradise",
"name": "COLISEUM PARADISE",
"area": "กรุงเทพฯ",
"distance": "—",
"categories": [
"หนังคลาสสิก",
"อาร์ตเฮาส์"
],
"description": null,
"address": null,
"map_url": null,
"transport": [],
"contacts": [],
"payments": [],
"facilities": [],
"hidden": false,
"image": null
}
]
}
View File
Whitespace-only changes.
+23 -10
View File
@@ -1,20 +1,33 @@
{
"name": "App",
"short_name": "App",
"description": "Agent-Native app starter ready to customize",
"start_url": "./",
"background_color": "#111111",
"theme_color": "#18181B",
"name": "AlterFlixHub — โรงหนังอิสระ",
"short_name": "AlterFlixHub",
"description": "ค้นหาโรงภาพยนตร์อิสระ ทางเลือกในการดูหนัง",
"lang": "th",
"dir": "ltr",
"start_url": "/",
"scope": "/",
"display": "standalone",
"background_color": "#0D0D0D",
"theme_color": "#0D0D0D",
"icons": [
{
"src": "icon-192.svg",
"src": "/icon-192.svg",
"sizes": "192x192",
"type": "image/svg+xml"
"type": "image/svg+xml",
"purpose": "any"
},
{
"src": "icon-512.svg",
"src": "/icon-512.svg",
"sizes": "512x512",
"type": "image/svg+xml"
"type": "image/svg+xml",
"purpose": "any"
}
],
"shortcuts": [
{
"name": "จัดการข้อมูล",
"short_name": "หลังบ้าน",
"url": "/admin"
}
]
}
+120
View File
@@ -0,0 +1,120 @@
/* AlterFlixHub Service Worker — PWA
* ------------------------------------------------------------
* ★ หน้าเว็บ (navigation) : network-first → ออฟไลน์ใช้แคช
* ★ ข้อมูล JSON (/data/) : network-first → กันข้อมูลค้างหลังแก้ในหลังบ้าน
* ★ ไฟล์นิ่ง (_assets, svg): cache-first + อัปเดตพื้นหลัง
* ★ ข้าม /_agent-native/ (API ของแพลตฟอร์ม) — ห้ามแคช
* ★ อัปเดตเวอร์ชัน: bump CACHE_VERSION แล้ว reload ครั้งเดียวตอน controllerchange
*/
const CACHE_VERSION = "alterflixhub-v1.1.0";
const PRECACHE = [
"/",
"/admin",
"/data/theaters.json",
"/manifest.json",
"/favicon.svg",
"/icon-192.svg",
"/icon-512.svg",
];
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_VERSION);
await Promise.all(
PRECACHE.map((url) =>
cache.add(new Request(url, { cache: "reload" })).catch(() => undefined),
),
);
await self.skipWaiting();
})(),
);
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
const keys = await caches.keys();
await Promise.all(
keys.filter((key) => key !== CACHE_VERSION).map((key) => caches.delete(key)),
);
await self.clients.claim();
})(),
);
});
self.addEventListener("message", (event) => {
if (event.data === "SKIP_WAITING") self.skipWaiting();
});
const isPlatformApi = (url) =>
url.pathname.startsWith("/_agent-native/") ||
url.pathname.startsWith("/api/") ||
url.pathname.startsWith("/.well-known/");
async function networkFirst(request, fallbackUrl) {
const cache = await caches.open(CACHE_VERSION);
try {
const response = await fetch(request);
if (response && response.ok) cache.put(request, response.clone());
return response;
} catch {
const cached = await cache.match(request);
if (cached) return cached;
if (fallbackUrl) {
const fallback = await cache.match(fallbackUrl);
if (fallback) return fallback;
}
return new Response("ออฟไลน์ — ไม่มีข้อมูลในแคช", {
status: 503,
headers: { "content-type": "text/plain; charset=utf-8" },
});
}
}
async function cacheFirst(request) {
const cache = await caches.open(CACHE_VERSION);
const cached = await cache.match(request);
if (cached) {
// อัปเดตพื้นหลัง (ไม่บล็อกการตอบ)
fetch(request)
.then((response) => {
if (response && response.ok) cache.put(request, response.clone());
})
.catch(() => undefined);
return cached;
}
const response = await fetch(request);
if (response && response.ok) cache.put(request, response.clone());
return response;
}
self.addEventListener("fetch", (event) => {
const { request } = event;
if (request.method !== "GET") return;
const url = new URL(request.url);
if (url.origin !== self.location.origin) return;
if (isPlatformApi(url)) return;
// เอกสารหน้าเว็บ
if (request.mode === "navigate") {
event.respondWith(networkFirst(request, "/"));
return;
}
// ข้อมูลจากไฟล์ JSON
if (url.pathname.startsWith("/data/")) {
event.respondWith(networkFirst(request));
return;
}
// ไฟล์นิ่ง
if (
url.pathname.startsWith("/assets/") ||
/\.(?:css|js|mjs|svg|png|jpg|jpeg|webp|woff2?|ttf)$/.test(url.pathname)
) {
event.respondWith(cacheFirst(request));
}
});
+6
View File
@@ -0,0 +1,6 @@
{
"version": "1.1.0",
"app": "alterflixhub",
"cache": "alterflixhub-v1.1.0",
"updated_at": "2026-10-27T02:30:00+07:00"
}