reboot alterflixhub

This commit is contained in:
Bkk1234 committed 2026-11-01 17:24:44 +07:00
commit 1e84023a44
188 files changed
+31629

No files matched your search

+300
View File
@@ -0,0 +1,300 @@
import { useState } from "react";
import type { AboutContent, AboutSection } from "@/lib/content-types";
import type { Locale } from "@/lib/i18n/messages";
const inputClass =
"w-full rounded-lg border border-[#303030] bg-[#141414] px-3 py-2 text-sm text-white outline-none transition focus:border-[#A92626] focus-visible:ring-2 focus-visible:ring-[#A92626]/40";
const labelClass = "flex flex-col gap-1.5 text-xs text-[#999]";
const buttonClass =
"min-h-11 rounded-lg border border-[#303030] px-3 text-sm transition hover:border-[#A92626] hover:text-[#D47272] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#A92626]";
const primaryButtonClass =
"min-h-11 rounded-lg bg-[#8F0808] px-4 text-sm font-medium transition hover:bg-[#a30a0a] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#D47272]";
const LOCALE_TABS: Array<{ code: Locale; label: string }> = [
{ code: "th", label: "ไทย" },
{ code: "en", label: "English" },
];
type AboutEditorProps = {
value: Record<Locale, AboutContent>;
defaults: Record<Locale, AboutContent>;
onChange: (next: Record<Locale, AboutContent>) => void;
onSave: () => void;
saving: boolean;
};
/**
* ตัวแก้ไขหน้า "เกี่ยวกับเรา" — แยกแท็บตามภาษา มีตัวอย่างหน้าเว็บให้ดูสด ๆ
* ฟิลด์ที่เว้นว่างจะถูกเซิร์ฟเวอร์คืนเป็นข้อความตั้งต้นให้อัตโนมัติ (sanitizeAbout)
*/
export function AboutEditor({
value,
defaults,
onChange,
onSave,
saving,
}: AboutEditorProps) {
const [locale, setLocale] = useState<Locale>("th");
const current = value[locale];
function patch(next: Partial<AboutContent>) {
onChange({ ...value, [locale]: { ...current, ...next } });
}
function patchSection(index: number, next: Partial<AboutSection>) {
patch({
sections: current.sections.map((section, i) =>
i === index ? { ...section, ...next } : section,
),
});
}
function moveSection(index: number, direction: -1 | 1) {
const target = index + direction;
if (target < 0 || target >= current.sections.length) return;
const sections = [...current.sections];
const [moved] = sections.splice(index, 1);
sections.splice(target, 0, moved);
patch({ sections });
}
function addSection() {
patch({
sections: [
...current.sections,
{ heading: `หัวข้อที่ ${current.sections.length + 1}`, body: "" },
],
});
}
function removeSection(index: number) {
patch({ sections: current.sections.filter((_, i) => i !== index) });
}
function restoreDefaults() {
onChange({ ...value, [locale]: defaults[locale] });
}
const titleMissing = current.title.trim() === "";
const leadTooLong = current.lead.length > 400;
return (
<div className="px-6 py-5">
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
<div
role="tablist"
aria-label="ภาษา"
className="flex items-center gap-1 rounded-lg border border-[#242424] bg-[#141414] p-1"
>
{LOCALE_TABS.map((tab) => (
<button
key={tab.code}
type="button"
role="tab"
aria-selected={locale === tab.code}
onClick={() => setLocale(tab.code)}
className={`min-h-9 rounded-md px-4 text-sm transition ${
locale === tab.code
? "bg-[#242424] font-semibold text-[#D47272]"
: "text-[#999] hover:text-white"
}`}
>
{tab.label}
</button>
))}
</div>
<div className="flex flex-wrap items-center gap-2">
<button type="button" className={buttonClass} onClick={restoreDefaults}>
คืนค่าตั้งต้น ({locale.toUpperCase()})
</button>
<button
type="button"
className={primaryButtonClass}
onClick={onSave}
disabled={saving}
>
{saving ? "กำลังบันทึก…" : "บันทึกหน้าเกี่ยวกับเรา"}
</button>
</div>
</div>
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
<div className="flex flex-col gap-4">
<label className={labelClass}>
หัวข้อหลัก (H1)
<input
className={inputClass}
value={current.title}
onChange={(event) => patch({ title: event.target.value })}
aria-describedby="about-title-help"
aria-invalid={titleMissing}
/>
<span
id="about-title-help"
className={titleMissing ? "text-[#D47272]" : "text-[#8A8A8A]"}
>
{titleMissing
? "ต้องมีหัวข้อ — ถ้าเว้นว่าง ระบบจะใช้ข้อความตั้งต้น"
: `แสดงบนสุดของหน้า · ${current.title.length}/80 ตัวอักษร`}
</span>
</label>
<label className={labelClass}>
ย่อหน้าแนะนำ (ใต้หัวข้อ)
<textarea
className={`${inputClass} min-h-24 leading-[1.7]`}
value={current.lead}
onChange={(event) => patch({ lead: event.target.value })}
aria-describedby="about-lead-help"
aria-invalid={leadTooLong}
/>
<span
id="about-lead-help"
className={leadTooLong ? "text-[#D47272]" : "text-[#8A8A8A]"}
>
{leadTooLong
? "ยาวเกิน 400 ตัวอักษร — บนมือถือจะอ่านยาก"
: `${current.lead.length}/400 ตัวอักษร`}
</span>
</label>
<fieldset className="flex flex-col gap-3">
<legend className="mb-1 text-xs text-[#999]">
ส่วนย่อย ({current.sections.length} ส่วน)
</legend>
{current.sections.map((section, index) => (
<div
key={index}
className="rounded-xl border border-[#242424] bg-[#141414] p-4"
>
<div className="mb-2 flex items-center justify-between gap-2">
<span className="text-xs text-[#8A8A8A]">ส่วนที่ {index + 1}</span>
<div className="flex items-center gap-1">
<button
type="button"
className="size-8 rounded-md text-[#999] transition hover:bg-[#242424] hover:text-white disabled:opacity-40"
onClick={() => moveSection(index, -1)}
disabled={index === 0}
aria-label={`เลื่อนส่วนที่ ${index + 1} ขึ้น`}
>
↑
</button>
<button
type="button"
className="size-8 rounded-md text-[#999] transition hover:bg-[#242424] hover:text-white disabled:opacity-40"
onClick={() => moveSection(index, 1)}
disabled={index === current.sections.length - 1}
aria-label={`เลื่อนส่วนที่ ${index + 1} ลง`}
>
↓
</button>
<button
type="button"
className="min-h-8 rounded-md px-2 text-xs text-[#D47272] transition hover:bg-[#242424]"
onClick={() => removeSection(index)}
>
ลบ
</button>
</div>
</div>
<label className={labelClass}>
หัวข้อย่อย
<input
className={inputClass}
value={section.heading}
onChange={(event) =>
patchSection(index, { heading: event.target.value })
}
/>
</label>
<label className={`${labelClass} mt-2`}>
เนื้อหา
<textarea
className={`${inputClass} min-h-24 leading-[1.75]`}
value={section.body}
onChange={(event) =>
patchSection(index, { body: event.target.value })
}
/>
</label>
</div>
))}
<button
type="button"
className={`${buttonClass} self-start`}
onClick={addSection}
>
+ เพิ่มส่วน
</button>
</fieldset>
<div className="rounded-xl border border-[#A92626]/40 bg-[#141414] p-4">
<p className="mb-3 text-xs text-[#999]">กล่องติดต่อ (ท้ายหน้า)</p>
<label className={labelClass}>
หัวข้อ
<input
className={inputClass}
value={current.contactHeading}
onChange={(event) =>
patch({ contactHeading: event.target.value })
}
/>
</label>
<label className={`${labelClass} mt-2`}>
ข้อความ
<textarea
className={`${inputClass} min-h-20 leading-[1.75]`}
value={current.contactNote}
onChange={(event) => patch({ contactNote: event.target.value })}
/>
</label>
</div>
</div>
<aside className="lg:sticky lg:top-24 lg:self-start">
<p className="mb-2 text-xs text-[#8A8A8A]">ตัวอย่างหน้าเว็บ (สด)</p>
<div className="rounded-xl border border-[#242424] bg-[#0D0D0D] p-4">
<h3 className="text-xl font-bold leading-[1.3]">
{current.title || "—"}
</h3>
<p className="mt-2 text-sm leading-[1.7] text-[#B3B3B3]">
{current.lead || "—"}
</p>
<div className="mt-3 flex flex-col gap-2">
{current.sections.map((section, index) => (
<div
key={index}
className="rounded-lg border border-[#242424] bg-[#141414] p-3"
>
<p className="text-sm font-semibold">{section.heading}</p>
<p className="mt-1 text-xs leading-[1.7] text-[#B3B3B3]">
{section.body}
</p>
</div>
))}
</div>
<div className="mt-3 rounded-lg border border-[#A92626]/50 bg-gradient-to-b from-[#8F0808]/20 to-transparent p-3">
<p className="text-sm font-semibold">{current.contactHeading}</p>
<p className="mt-1 text-xs leading-[1.7] text-[#B3B3B3]">
{current.contactNote}
</p>
</div>
</div>
<a
href={`/about?lang=${locale}`}
target="_blank"
rel="noreferrer"
className="mt-3 inline-flex min-h-11 items-center text-xs text-[#D47272] underline-offset-4 hover:underline"
>
เปิดหน้า /about?lang={locale} ↗
</a>
</aside>
</div>
</div>
);
}
+51
View File
@@ -0,0 +1,51 @@
import { IconChevronRight } from "@tabler/icons-react";
import type { ReactNode } from "react";
/**
* หมวดการ์ดแบบพับได้ของหลังบ้าน (ใช้ <details> เนทีฟ — คีย์บอร์ดและ screen reader ทำงานได้เอง)
* ค่าเริ่มต้น = พับเก็บ เพื่อไม่ให้หน้าแอดมินยืดยาว
*/
type Props = {
title: string;
description?: string;
/** ข้อความสั้น ๆ เช่นจำนวนรายการ */
badge?: string;
defaultOpen?: boolean;
children: ReactNode;
};
export function AdminSection({
title,
description,
badge,
defaultOpen = false,
children,
}: Props) {
return (
<details
open={defaultOpen}
className="group overflow-hidden rounded-xl border border-[#242424] bg-[#111111]"
>
<summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-4 py-3 transition hover:bg-[#171717] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-[#A92626] [&::-webkit-details-marker]:hidden">
<span className="flex min-w-0 items-center gap-2">
<IconChevronRight
size={16}
className="shrink-0 text-[#8F8F8F] transition-transform group-open:rotate-90"
/>
<span className="truncate text-sm font-medium">{title}</span>
{badge ? (
<span className="shrink-0 rounded-full bg-[#242424] px-2 py-0.5 text-[11px] text-[#B3B3B3]">
{badge}
</span>
) : null}
</span>
{description ? (
<span className="hidden shrink-0 text-[11px] text-[#777] sm:block">
{description}
</span>
) : null}
</summary>
<div className="border-t border-[#242424] px-4 py-4">{children}</div>
</details>
);
}
+82
View File
@@ -0,0 +1,82 @@
type ChipOption = {
value: string;
label: string;
};
type ChipPickerProps = {
options: ChipOption[];
selected: string[];
onToggle: (value: string) => void;
/** ข้อความเมื่อยังไม่ได้เลือกอะไร */
emptyHint?: string;
};
/**
* ปุ่มเลือกหลายค่าแบบชิป สำหรับหลังบ้าน (หมวดหมู่ / สิ่งอำนวยความสะดวก)
* ค่าที่เลือกจะถูกเก็บตามลำดับ options เสมอ เพื่อให้ข้อมูลในไฟล์นิ่ง
*/
export function ChipPicker({
options,
selected,
onToggle,
emptyHint,
}: ChipPickerProps) {
const chosen = new Set(selected);
const known = new Set(options.map((option) => option.value));
const extras = selected.filter((value) => !known.has(value));
return (
<div className="flex flex-wrap gap-2">
{options.map((option) => {
const active = chosen.has(option.value);
return (
<button
key={option.value}
type="button"
aria-pressed={active}
onClick={() => onToggle(option.value)}
className={`rounded-full border px-3 py-1 text-xs transition ${
active
? "border-[#A92626] bg-[rgba(143,8,8,0.18)] text-[#D47272]"
: "border-[#303030] text-[#999] hover:border-[#A92626] hover:text-white"
}`}
>
{option.label}
</button>
);
})}
{extras.map((value) => (
<button
key={value}
type="button"
aria-pressed
onClick={() => onToggle(value)}
className="rounded-full border border-[#A92626] bg-[rgba(143,8,8,0.18)] px-3 py-1 text-xs text-[#D47272] transition hover:border-[#D47272]"
>
{value}
</button>
))}
{options.length === 0 && extras.length === 0 && emptyHint ? (
<span className="text-xs text-[#777]">{emptyHint}</span>
) : null}
</div>
);
}
/**
* สลับค่าหนึ่งตัวในลิสต์ แล้วเรียงตามลำดับ options (ค่าที่ไม่รู้จักต่อท้าย)
*/
export function toggleValue(
selected: string[],
value: string,
order: string[],
): string[] {
const next = selected.includes(value)
? selected.filter((item) => item !== value)
: [...selected, value];
const rank = (item: string) => {
const index = order.indexOf(item);
return index < 0 ? order.length + 1 : index;
};
return [...next].sort((a, b) => rank(a) - rank(b));
}
@@ -0,0 +1,105 @@
import type { Cinema } from "@/lib/cinemas";
import { DEFAULT_LOCALE, MESSAGES, type FacilityKey } from "@/lib/i18n/messages";
/**
* แก้ข้อความสิ่งอำนวยความสะดวก "ของโรงนี้" (ผูกกับโรง ไม่ใช่ส่วนกลาง)
*
* - ชื่อหัวข้อ: ช่องเดียว (ใช้ทั้ง TH/EN) — ว่าง = ใช้ค่าเริ่มต้นจาก messages.ts
* - คำอธิบาย TH/EN: แสดงเฉพาะโรงที่ต้องการ (hasDescriptions) เช่น เฮ้าส์ สามย่าน
* ที่มีข้อมูลครบแล้ว โรงอื่นไม่ต้องกรอก
*/
export type FacilityDetail = {
label?: string;
sub_th?: string;
sub_en?: string;
};
const ADMIN_MESSAGES = MESSAGES[DEFAULT_LOCALE];
type Props = {
facilities: FacilityKey[];
details: NonNullable<Cinema["facility_details"]>;
hasDescriptions: boolean;
onChange: (next: NonNullable<Cinema["facility_details"]>) => void;
inputClass: string;
labelClass: string;
};
export function CinemaFacilitiesEditor({
facilities,
details,
hasDescriptions,
onChange,
inputClass,
labelClass,
}: Props) {
if (facilities.length === 0) {
return (
<span className="text-[11px] text-[#777]">
เลือกหัวข้อด้านบนก่อน แล้วค่อยใส่ชื่อที่ต้องการ
</span>
);
}
function update(key: FacilityKey, patch: FacilityDetail) {
const current = details[key] ?? {};
const next: FacilityDetail = { ...current, ...patch };
const cleaned: FacilityDetail = {};
if (next.label?.trim()) cleaned.label = next.label;
if (next.sub_th?.trim()) cleaned.sub_th = next.sub_th;
if (next.sub_en?.trim()) cleaned.sub_en = next.sub_en;
onChange({ ...details, [key]: cleaned });
}
return (
<div className="flex flex-col gap-2">
{facilities.map((key) => {
const fallback = ADMIN_MESSAGES.facilities[key];
const detail = details[key] ?? {};
return (
<div
key={key}
className="grid gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-2"
>
<label className={labelClass}>
ชื่อหัวข้อ
<input
className={inputClass}
value={detail.label ?? ""}
placeholder={fallback.title}
onChange={(event) => update(key, { label: event.target.value })}
/>
</label>
{hasDescriptions ? (
<>
<label className={labelClass}>
คำอธิบาย (TH)
<input
className={inputClass}
value={detail.sub_th ?? ""}
placeholder={fallback.sub}
onChange={(event) =>
update(key, { sub_th: event.target.value })
}
/>
</label>
<label className={labelClass}>
คำอธิบาย (EN)
<input
className={inputClass}
value={detail.sub_en ?? ""}
placeholder={MESSAGES.en.facilities[key].sub}
onChange={(event) =>
update(key, { sub_en: event.target.value })
}
/>
</label>
</>
) : null}
</div>
);
})}
</div>
);
}
+253
View File
@@ -0,0 +1,253 @@
import {
IconArrowDown,
IconArrowUp,
IconGripVertical,
IconSortAscendingLetters,
} from "@tabler/icons-react";
import { useMemo, useState } from "react";
import type { Cinema } from "@/lib/cinemas";
/**
* รายชื่อโรงหนังในหลังบ้าน — เรียง ก-ฮ และสลับตำแหน่งได้
*
* - โหมด "ลำดับที่จัดไว้": ลากวางสลับที่ หรือกด ↑ ↓ (ใช้เมาส์/คีย์บอร์ดได้ทั้งคู่)
* ลำดับที่ได้คือลำดับเดียวกับที่หน้าเว็บแสดง (อาร์เรย์ cinemas ใน content.json)
* - โหมด "ก-ฮ": เรียงตามชื่อไทยด้วย Intl.Collator("th") — ยังไม่บันทึกจนกว่าจะกด "ใช้ลำดับนี้"
* (กันเข้าใจผิดว่าลากในโหมดเรียงได้)
*/
const thaiCollator = new Intl.Collator("th", {
sensitivity: "base",
numeric: true,
});
function sortKey(cinema: Cinema): string {
return (cinema.name_th?.trim() || cinema.name || "").trim();
}
/** เรียงชื่อโรงหนังภาษาไทยตามพจนานุกรม ก-ฮ */
export function sortCinemasByName(cinemas: Cinema[]): Cinema[] {
return [...cinemas].sort((a, b) => thaiCollator.compare(sortKey(a), sortKey(b)));
}
/** เทียบว่าสองลิสต์มี slug เรียงเหมือนกันหรือยัง */
export function hasSameOrder(a: Cinema[], b: Cinema[]): boolean {
if (a.length !== b.length) return false;
return a.every((cinema, index) => cinema.slug === b[index]?.slug);
}
/** ย้ายโรงหนังจากตำแหน่งหนึ่งไปแทรกก่อน/หลังอีกตัว */
export function moveCinema(
cinemas: Cinema[],
fromSlug: string,
toSlug: string,
position: "before" | "after" = "before",
): Cinema[] {
if (fromSlug === toSlug) return cinemas;
const from = cinemas.findIndex((item) => item.slug === fromSlug);
const target = cinemas.findIndex((item) => item.slug === toSlug);
if (from < 0 || target < 0) return cinemas;
const next = [...cinemas];
const [moved] = next.splice(from, 1);
const insertAt = next.findIndex((item) => item.slug === toSlug);
if (insertAt < 0) return cinemas;
next.splice(position === "after" ? insertAt + 1 : insertAt, 0, moved);
return next;
}
/** เลื่อนขึ้น/ลงทีละหนึ่งตำแหน่ง (สำหรับปุ่มลูกศร) */
export function shiftCinema(cinemas: Cinema[], slug: string, delta: number): Cinema[] {
const from = cinemas.findIndex((item) => item.slug === slug);
const to = from + delta;
if (from < 0 || to < 0 || to >= cinemas.length) return cinemas;
const next = [...cinemas];
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved);
return next;
}
type SortMode = "manual" | "thai";
type CinemaListProps = {
cinemas: Cinema[];
selected: string | null;
/** ลำดับในหน้าเว็บยังไม่ตรงกับที่บันทึกไว้หรือไม่ */
dirty: boolean;
saving: boolean;
onSelect: (slug: string) => void;
onReorder: (next: Cinema[]) => void;
onSaveOrder: () => void;
};
const modeButtonClass = (active: boolean) =>
`flex-1 rounded-md px-2 py-1 text-[11px] transition ${
active ? "bg-[#242424] text-[#D47272]" : "text-[#999] hover:text-white"
}`;
const arrowButtonClass =
"flex size-6 items-center justify-center rounded text-[#777] transition hover:bg-[#242424] hover:text-white disabled:pointer-events-none disabled:opacity-30";
export function CinemaList({
cinemas,
selected,
dirty,
saving,
onSelect,
onReorder,
onSaveOrder,
}: CinemaListProps) {
const [mode, setMode] = useState<SortMode>("manual");
const [dragSlug, setDragSlug] = useState<string | null>(null);
const [overSlug, setOverSlug] = useState<string | null>(null);
const visible = useMemo(
() => (mode === "thai" ? sortCinemasByName(cinemas) : cinemas),
[cinemas, mode],
);
function handleDrop(event: React.DragEvent<HTMLLIElement>, toSlug: string) {
event.preventDefault();
const fromSlug = dragSlug ?? event.dataTransfer.getData("text/plain");
setOverSlug(null);
setDragSlug(null);
if (!fromSlug || fromSlug === toSlug) return;
onReorder(moveCinema(cinemas, fromSlug, toSlug));
}
return (
<div className="mt-2 flex flex-col gap-2">
<div className="flex items-center gap-1 rounded-lg border border-[#303030] p-1">
<button
type="button"
className={modeButtonClass(mode === "manual")}
aria-pressed={mode === "manual"}
onClick={() => setMode("manual")}
>
ลำดับที่จัดไว้
</button>
<button
type="button"
className={modeButtonClass(mode === "thai")}
aria-pressed={mode === "thai"}
onClick={() => setMode("thai")}
>
<span className="inline-flex items-center justify-center gap-1">
<IconSortAscendingLetters size={13} /> ก-ฮ
</span>
</button>
</div>
{mode === "thai" ? (
<div className="rounded-lg border border-[#303030] bg-[#141414] p-2 text-[11px] leading-[1.7] text-[#999]">
เรียงตามชื่อไทย ก-ฮ · โหมดนี้ลากสลับไม่ได้
<button
type="button"
className="mt-1 block w-full rounded-md border border-[#303030] px-2 py-1 text-[11px] text-[#D47272] transition hover:border-[#A92626]"
onClick={() => {
onReorder(sortCinemasByName(cinemas));
setMode("manual");
}}
>
ใช้ลำดับ ก-ฮ นี้ (แล้วกดบันทึก)
</button>
</div>
) : (
<p className="px-1 text-[11px] leading-[1.6] text-[#777]">
ลากชื่อเพื่อสลับตำแหน่ง หรือกด ↑ ↓ ทีละขั้น
</p>
)}
{dirty ? (
<button
type="button"
disabled={saving}
className="rounded-lg bg-[#8F0808] px-3 py-1.5 text-[11px] font-medium transition hover:bg-[#a30a0a] disabled:opacity-60"
onClick={onSaveOrder}
>
{saving ? "กำลังบันทึก…" : "บันทึกลำดับใหม่"}
</button>
) : null}
<ul className="flex max-h-[62vh] flex-col gap-1 overflow-y-auto pr-1">
{visible.map((item, index) => {
const isSelected = item.slug === selected;
const isDragging = dragSlug === item.slug;
const isOver = overSlug === item.slug && dragSlug !== item.slug;
return (
<li
key={item.slug}
draggable={mode === "manual"}
onDragStart={(event) => {
setDragSlug(item.slug);
event.dataTransfer.effectAllowed = "move";
event.dataTransfer.setData("text/plain", item.slug);
}}
onDragOver={(event) => {
if (mode !== "manual") return;
event.preventDefault();
event.dataTransfer.dropEffect = "move";
setOverSlug(item.slug);
}}
onDragLeave={() => {
setOverSlug((current) => (current === item.slug ? null : current));
}}
onDrop={(event) => handleDrop(event, item.slug)}
onDragEnd={() => {
setDragSlug(null);
setOverSlug(null);
}}
className={`group flex items-center gap-1 rounded-lg pr-1 transition ${
isSelected ? "bg-[#242424]" : "hover:bg-[#1B1B1B]"
} ${isDragging ? "opacity-40" : ""} ${
isOver ? "outline outline-2 outline-offset-[-2px] outline-[#A92626]" : ""
} ${mode === "manual" ? "cursor-grab active:cursor-grabbing" : ""}`}
>
<span
aria-hidden="true"
className={`pl-1 ${
mode === "manual" ? "text-[#555] group-hover:text-[#999]" : "text-transparent"
}`}
>
<IconGripVertical size={14} />
</span>
<button
type="button"
onClick={() => onSelect(item.slug)}
className={`min-w-0 flex-1 py-2 text-left text-sm transition ${
isSelected ? "text-[#D47272]" : "text-[#B3B3B3] hover:text-white"
}`}
>
<span className="block truncate">{item.name_th || item.name}</span>
<span className="block truncate text-[10px] text-[#777]">{item.slug}</span>
</button>
{mode === "manual" ? (
<span className="flex flex-col">
<button
type="button"
className={arrowButtonClass}
aria-label={`เลื่อน ${item.name_th || item.name} ขึ้น`}
disabled={index === 0}
onClick={() => onReorder(shiftCinema(cinemas, item.slug, -1))}
>
<IconArrowUp size={13} />
</button>
<button
type="button"
className={arrowButtonClass}
aria-label={`เลื่อน ${item.name_th || item.name} ลง`}
disabled={index === visible.length - 1}
onClick={() => onReorder(shiftCinema(cinemas, item.slug, 1))}
>
<IconArrowDown size={13} />
</button>
</span>
) : null}
</li>
);
})}
</ul>
</div>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { useEffect, useState } from "react";
/**
* ช่องกรอกหลายค่า คั่นด้วย "," (เช่น หมวด, ช่องทางชำระเงิน)
*
* ทำไมต้องมี draft: ถ้าผูก value เข้ากับ array ตรง ๆ แล้ว split/join ทุกคีย์
* ตัว "," ที่เพิ่งพิมพ์จะถูกตัดทิ้งทันที ( join(", ") ไม่มีตัวคั่นให้ค่าว่าง )
* ทำให้พิมพ์คั่นค่าไม่ได้เลย — draft เก็บข้อความดิบระหว่างพิมพ์ แล้วค่อย
* normalize เป็น ", " เมื่อออกจากช่อง
*/
/** แปลงข้อความ → รายการ (รับ , , 、 และขึ้นบรรทัดใหม่เป็นตัวคั่นด้วย) */
export function parseCommaList(value: string): string[] {
return value
.replace(/[,、]/g, ",")
.split(/[,\n]/)
.map((item) => item.trim())
.filter((item) => item !== "");
}
export function formatList(value: string[]): string {
return value.join(", ");
}
type CommaListInputProps = {
value: string[];
onChangeValue: (next: string[]) => void;
className?: string;
placeholder?: string;
id?: string;
};
export function CommaListInput({
value,
onChangeValue,
className,
placeholder,
id,
}: CommaListInputProps) {
const canonical = formatList(value);
const [draft, setDraft] = useState<string | null>(null);
// ค่าถูกเปลี่ยนจากที่อื่น (เช่น เปลี่ยนโรง / ใช้ JSON / คืนค่า) → ทิ้ง draft
useEffect(() => {
if (draft === null) return;
if (formatList(parseCommaList(draft)) !== canonical) setDraft(null);
}, [canonical, draft]);
return (
<input
id={id}
className={className}
placeholder={placeholder}
value={draft ?? canonical}
spellCheck={false}
onChange={(event) => {
const text = event.target.value;
setDraft(text);
onChangeValue(parseCommaList(text));
}}
onBlur={() => setDraft(null)}
/>
);
}
+113
View File
@@ -0,0 +1,113 @@
import { IconPlus, IconTrash } from "@tabler/icons-react";
import type { ContactChannel } from "@/lib/cinemas";
/**
* แก้ช่องทางติดต่อของการ์ด "สอบถามข้อมูลและจองตั๋ว" ต่อโรง
* แต่ละแถว = label / ค่าที่แสดง / ลิงก์ (ถ้าไม่มีลิงก์ หน้าเว็บแสดงเป็นข้อความธรรมดา)
*/
const SUGGESTED_LABELS = [
"Website",
"Facebook",
"Instagram",
"Line",
"Call",
"อีเมล",
"จองตั๋ว",
];
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]";
type Props = {
contacts: ContactChannel[];
onChange: (next: ContactChannel[]) => void;
inputClass: string;
labelClass: string;
};
export function ContactsEditor({ contacts, onChange, inputClass, labelClass }: Props) {
function updateAt(index: number, patch: Partial<ContactChannel>) {
onChange(
contacts.map((item, i) => (i === index ? { ...item, ...patch } : item)),
);
}
return (
<div className="flex flex-col gap-2">
<span className="text-xs text-[#999]">ช่องทางติดต่อ / จองตั๋ว</span>
{contacts.length === 0 ? (
<span className="text-[11px] text-[#777]">
ยังไม่มีช่องทางติดต่อ — หน้าเว็บจะขึ้น “ยังไม่ระบุช่องทางติดต่อ”
</span>
) : null}
{contacts.map((contact, index) => (
<div
key={index}
className="grid gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-[130px_minmax(0,1fr)_minmax(0,1fr)_auto]"
>
<label className={labelClass}>
ป้ายชื่อ
<input
className={inputClass}
value={contact.label}
placeholder="Website"
list="contact-label-options"
onChange={(event) => updateAt(index, { label: event.target.value })}
/>
</label>
<label className={labelClass}>
ข้อความที่แสดง
<input
className={inputClass}
value={contact.value}
placeholder="www.housesamyan.com"
onChange={(event) => updateAt(index, { value: event.target.value })}
/>
</label>
<label className={labelClass}>
ลิงก์ (ไม่บังคับ)
<input
className={inputClass}
value={contact.href ?? ""}
placeholder="https://… หรือ tel:+66…"
onChange={(event) =>
updateAt(index, {
href: event.target.value.trim() === "" ? null : event.target.value,
})
}
/>
</label>
<div className="flex items-end">
<button
type="button"
className={smallButtonClass}
aria-label={`ลบช่องทางที่ ${index + 1}`}
onClick={() => onChange(contacts.filter((_, i) => i !== index))}
>
<IconTrash size={14} />
</button>
</div>
</div>
))}
<datalist id="contact-label-options">
{SUGGESTED_LABELS.map((label) => (
<option key={label} value={label} />
))}
</datalist>
<button
type="button"
className={`${smallButtonClass} w-fit`}
onClick={() => onChange([...contacts, { label: "", value: "", href: null }])}
>
<IconPlus size={14} />
เพิ่มช่องทางติดต่อ
</button>
</div>
);
}
+106
View File
@@ -0,0 +1,106 @@
import { IconPlus, IconTrash } from "@tabler/icons-react";
/**
* แก้รายการรูปโรงหนัง (อาร์เรย์ `photos`) — ใส่เป็น URL หรือ path ในโปรเจกต์
* รูปแรกใช้เป็นภาพหลักของแกลเลอรี · ลากสลับลำดับไม่ได้ ใช้ปุ่ม ↑/↓ แทน
*/
type Props = {
photos: string[];
onChange: (next: string[]) => void;
inputClass: string;
labelClass: 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]";
export function PhotosEditor({ photos, onChange, inputClass, labelClass }: Props) {
function updateAt(index: number, value: string) {
onChange(photos.map((item, i) => (i === index ? value : item)));
}
return (
<div className="flex flex-col gap-2">
<span className="text-xs text-[#999]">รูปภาพโรงหนัง</span>
{photos.length === 0 ? (
<span className="text-[11px] text-[#777]">
ยังไม่มีรูป — หน้าเว็บจะแสดงช่องแทน (ภาพที่ 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>
))}
<button
type="button"
className={`${smallButtonClass} w-fit`}
onClick={() => onChange([...photos, ""])}
>
<IconPlus size={14} />
เพิ่มรูป
</button>
</div>
);
}
+120
View File
@@ -0,0 +1,120 @@
import { useEffect, useRef, useState } from "react";
/**
* ช่องแก้ slug (ใช้ใน URL) ของโรงหนัง
*
* ทำไมของเดิม "แก้ไม่ได้": อินพุตผูกกับ `cinema.slug` ตรง ๆ และแปลงค่าทุกคีย์
* (`replace(/[^a-z0-9-]/g, "-")`) — พอพิมพ์ตัวอักษรไทย/เว้นวรรค มันกลายเป็น "-"
* ทันที และถ้าลบจนว่าง ค่าก็ว่างทันที ทำให้ดูเหมือนพิมพ์อะไรไม่ได้เลย
*
* ที่นี่เก็บ "ข้อความดิบ" ระหว่างพิมพ์ (draft) แล้วค่อยจัดรูปตอนออกจากช่อง (blur)
* slug ว่างหรือซ้ำกับโรงอื่นจะไม่ถูกบันทึก — คืนค่าเดิมให้
*/
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
/** จัดรูป slug: ตัวเล็ก, ช่องว่าง/ขีดซ้ำ → ขีดเดียว, ตัดอักขระที่ไม่ใช่ a-z0-9- */
export function normalizeSlug(value: string): string {
return value
.trim()
.toLowerCase()
.replace(/[\s_]+/g, "-")
.replace(/[^a-z0-9-]/g, "")
.replace(/-{2,}/g, "-")
.replace(/^-+|-+$/g, "");
}
/**
* แนะนำ slug จากชื่อโรงหนังภาษาอังกฤษ
* "HOUSE CINEMA SAMYAN" → "house-cinema-samyan" · "." และอักขระอื่นถูกตัดให้เอง
*/
export function suggestSlug(name: string): string {
return normalizeSlug(
name
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/&/g, " and ")
.replace(/['’]/g, ""),
);
}
/** เหตุผลที่ slug ใช้ไม่ได้ (null = ใช้ได้) */
export function slugProblem(
slug: string,
options: { others: string[]; self?: string },
): string | null {
if (slug === "") return "slug ว่างไม่ได้";
if (!SLUG_PATTERN.test(slug)) return "ใช้ได้เฉพาะ a-z, 0-9 และ - (ห้ามขีดติดกัน/หัวท้าย)";
if (options.others.some((other) => other === slug && other !== options.self)) {
return "slug นี้มีโรงอื่นใช้อยู่";
}
return null;
}
type SlugInputProps = {
value: string;
/** slug ของโรงอื่นทั้งหมด ใช้ตรวจซ้ำ */
others: string[];
onChange: (slug: string) => void;
className?: string;
};
export function SlugInput({ value, others, onChange, className }: SlugInputProps) {
const [draft, setDraft] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const lastValue = useRef(value);
// ค่าถูกเปลี่ยนจากภายนอก (สลับโรง / ใช้ JSON / คืนค่า) → ทิ้ง draft
// เทียบกับค่าก่อนหน้า ไม่ใช่เทียบกับ draft เพราะระหว่างพิมพ์ value ยังไม่เปลี่ยน
useEffect(() => {
if (lastValue.current === value) return;
lastValue.current = value;
setDraft(null);
}, [value]);
const shown = draft ?? value;
const preview = normalizeSlug(shown);
const problem = slugProblem(preview, { others, self: value });
const dirty = preview !== value;
return (
<div className="flex flex-col gap-1">
<input
className={className}
value={shown}
spellCheck={false}
placeholder="house-cinema-samyan"
onChange={(event) => {
setDraft(event.target.value);
setNotice(null);
}}
onBlur={() => {
const next = normalizeSlug(draft ?? value);
if (next !== "" && slugProblem(next, { others, self: value }) === null) {
if (next !== value) {
onChange(next);
setNotice("เปลี่ยน slug แล้ว — ลิงก์เดิมของโรงนี้จะใช้ไม่ได้ (ต้องกดบันทึก)");
}
} else if (next !== value) {
setNotice("slug ไม่ถูกบันทึก (ว่าง/ซ้ำ/รูปแบบไม่ถูก) — คงค่าเดิมไว้");
}
setDraft(null);
}}
/>
<div className="flex flex-wrap items-center gap-2 text-[11px]">
<code className="text-[#777]">/cinema/{preview || "…"}</code>
{problem && dirty ? (
<span className="text-[#D47272]">{problem}</span>
) : null}
{!problem && dirty ? (
<span className="text-[#B3B3B3]">กด Tab/คลิกออกเพื่อยืนยัน slug ใหม่</span>
) : null}
</div>
{notice ? (
<span className="text-[11px] text-[#D47272]">{notice}</span>
) : null}
</div>
);
}
+116
View File
@@ -0,0 +1,116 @@
import { IconPlus, IconTrash } from "@tabler/icons-react";
import type { TransportMode } from "@/lib/cinemas";
import { DEFAULT_LOCALE, MESSAGES } from "@/lib/i18n/messages";
/**
* แก้ไขข้อมูลการเดินทางของโรงหนัง (รถยนต์ส่วนตัว / รถไฟฟ้า / รถประจำทาง)
* เรียงตามลำดับในอาร์เรย์ transport ของ content.json
*/
const ADMIN_MESSAGES = MESSAGES[DEFAULT_LOCALE];
const ICON_OPTIONS: Array<TransportMode["icon_name"]> = [
"private_car",
"metro",
"bus",
];
type TransportEditorProps = {
value: TransportMode[];
onChange: (next: TransportMode[]) => void;
inputClass: string;
labelClass: 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]";
export function TransportEditor({
value,
onChange,
inputClass,
labelClass,
}: TransportEditorProps) {
function updateAt(index: number, patch: Partial<TransportMode>) {
onChange(value.map((item, i) => (i === index ? { ...item, ...patch } : item)));
}
return (
<div className="flex flex-col gap-2">
<span className="text-xs text-[#999]">การเดินทาง</span>
{value.length === 0 ? (
<span className="text-[11px] text-[#777]">
ยังไม่มีข้อมูล — หน้าเว็บจะซ่อนบล็อกการเดินทาง
</span>
) : null}
{value.map((route, index) => (
<div
key={index}
className="grid gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-[130px_minmax(0,1fr)_minmax(0,1fr)_auto]"
>
<label className={labelClass}>
วิธีเดินทาง
<select
className={inputClass}
value={route.icon_name}
onChange={(event) =>
updateAt(index, {
icon_name: event.target.value as TransportMode["icon_name"],
})
}
>
{ICON_OPTIONS.map((icon) => (
<option key={icon} value={icon}>
{ADMIN_MESSAGES.transport[icon]}
</option>
))}
</select>
</label>
<label className={labelClass}>
รายละเอียด (TH)
<input
className={inputClass}
value={route.value}
placeholder="MRT สถานีสามย่าน"
onChange={(event) => updateAt(index, { value: event.target.value })}
/>
</label>
<label className={labelClass}>
รายละเอียด (EN)
<input
className={inputClass}
value={route.value_en ?? ""}
placeholder="MRT Sam Yan station"
onChange={(event) =>
updateAt(index, { value_en: event.target.value })
}
/>
</label>
<div className="flex items-end">
<button
type="button"
className={smallButtonClass}
aria-label={`ลบวิธีเดินทางลำดับที่ ${index + 1}`}
onClick={() => onChange(value.filter((_, i) => i !== index))}
>
<IconTrash size={14} />
</button>
</div>
</div>
))}
<button
type="button"
className={`${smallButtonClass} w-fit`}
onClick={() =>
onChange([...value, { icon_name: "bus", value: "", value_en: "" }])
}
>
<IconPlus size={14} />
เพิ่มวิธีเดินทาง
</button>
</div>
);
}
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import { parseCommaList, formatList } from "@/components/admin/CommaListInput";
import { normalizeSlug, slugProblem, suggestSlug } from "@/components/admin/SlugInput";
/**
* สเปกของตัวช่วยในหลังบ้าน — กันบั๊กที่เคยเจอจริง
* 1) ช่องคั่นด้วย "," ที่กลืนตัวคั่นระหว่างพิมพ์
* 2) slug ที่พิมพ์ไทย/เว้นวรรคแล้วหาย
*/
describe("parseCommaList", () => {
it("แยกด้วย , และตัดช่องว่างหัวท้าย", () => {
expect(parseCommaList("อาร์ตเฮาส์, สารคดี")).toEqual(["อาร์ตเฮาส์", "สารคดี"]);
});
it("ทิ้งค่าว่าง และรับตัวคั่นเต็มความกว้าง/ขึ้นบรรทัดใหม่", () => {
expect(parseCommaList("เงินสด, , โอน")).toEqual(["เงินสด", "โอน"]);
expect(parseCommaList("เงินสด,โอน")).toEqual(["เงินสด", "โอน"]);
expect(parseCommaList("ก\nข")).toEqual(["ก", "ข"]);
});
it("ค่าว่างได้อาร์เรย์ว่าง", () => {
expect(parseCommaList(" ")).toEqual([]);
});
});
describe("formatList", () => {
it("ต่อด้วย ', ' เสมอ", () => {
expect(formatList(["a", "b"])).toBe("a, b");
expect(formatList([])).toBe("");
});
});
describe("normalizeSlug", () => {
it("ตัวเล็ก + ช่องว่างเป็นขีด", () => {
expect(normalizeSlug("Mecani Cinema")).toBe("mecani-cinema");
});
it("ตัดอักขระที่ไม่ใช่ a-z0-9- และยุบขีดซ้ำ", () => {
expect(normalizeSlug(" HOUSE & Co. ")).toBe("house-co");
expect(normalizeSlug("a__b")).toBe("a-b");
expect(normalizeSlug("--a--b--")).toBe("a-b");
});
it("ภาษาไทยล้วนได้ค่าว่าง (ไม่ยอมให้บันทึก พร้อมเหตุผล)", () => {
expect(normalizeSlug("เมคานี ใหม่")).toBe("");
expect(slugProblem("", { others: [] })).toBe("slug ว่างไม่ได้");
});
});
describe("suggestSlug", () => {
it("แปลงชื่ออังกฤษเป็น slug", () => {
expect(suggestSlug("HOUSE CINEMA SAMYAN")).toBe("house-cinema-samyan");
expect(suggestSlug("MECANI")).toBe("mecani");
});
it("& กลายเป็น 'and' และตัด apostrophe", () => {
expect(suggestSlug("Doc Club & Friends")).toBe("doc-club-and-friends");
expect(suggestSlug("O'Brien Cinema")).toBe("obrien-cinema");
});
it("ตัดเสียง accent", () => {
expect(suggestSlug("Café Lumière")).toBe("cafe-lumiere");
});
});
describe("slugProblem", () => {
it("ซ้ำกับโรงอื่น = ใช้ไม่ได้", () => {
expect(
slugProblem("mecani", { others: ["mecani", "loprama"], self: "loprama" }),
).toBe("slug นี้มีโรงอื่นใช้อยู่");
});
it("ซ้ำกับตัวเอง = ผ่าน (ตอนแก้ฟิลด์อื่น)", () => {
expect(slugProblem("mecani", { others: ["mecani"], self: "mecani" })).toBeNull();
});
it("รูปแบบผิด เช่นขีดหัว/ท้าย = ใช้ไม่ได้", () => {
expect(slugProblem("-mecani", { others: [] })).toContain("a-z");
expect(slugProblem("mecani--x", { others: [] })).toContain("a-z");
});
});
+26
View File
@@ -0,0 +1,26 @@
import { Link } from "react-router";
import { SiteShell } from "@/components/site/SiteShell";
import { useI18n } from "@/lib/i18n";
import { COLORS } from "@/lib/design-tokens";
/** หน้า fallback เมื่อ slug ไม่ตรงกับโรงหนังที่มีอยู่ */
export function CinemaNotFound() {
const { messages } = useI18n();
return (
<SiteShell variant="detail">
<main className="relative z-10 mx-auto flex max-w-[1440px] flex-col items-center gap-6 px-5 py-32 text-center md:px-[108px]">
<h1 className="text-3xl font-bold">{messages.notFound.title}</h1>
<p className="text-[#B3B3B3]">{messages.notFound.text}</p>
<Link
to="/"
className="rounded-lg px-6 py-2 font-medium"
style={{ background: COLORS.brand }}
>
{messages.notFound.cta}
</Link>
</main>
</SiteShell>
);
}
+60
View File
@@ -0,0 +1,60 @@
import { IconMap, IconMapPin } from "@tabler/icons-react";
import {
cinemaDescription,
cinemaLocationLabel,
cinemaName,
type Cinema,
} from "@/lib/cinemas";
import { useI18n } from "@/lib/i18n";
import { COLORS } from "@/lib/design-tokens";
/** หัวโรงหนัง: ป้ายประเภท + ชื่อ + ที่ตั้ง + ปุ่มแผนที่ + คำอธิบาย */
export function CinemaSummary({ cinema }: { cinema: Cinema }) {
const { locale, messages } = useI18n();
const locationLabel = cinemaLocationLabel(cinema, locale);
const description = cinemaDescription(cinema, locale);
return (
<div className="flex flex-col gap-6">
<div className="flex flex-col gap-4">
<div className="flex flex-wrap gap-2">
{cinema.tags.map((tag) => (
<span
key={tag}
className="rounded-[18px] border border-[#A92626] px-4 py-2 text-sm text-[#D47272]"
style={{ background: COLORS.pillGradient }}
>
{messages.tags[tag] ?? tag}
</span>
))}
</div>
<h1 className="text-[40px] font-bold leading-[1.3]">
{cinemaName(cinema, locale)}
</h1>
</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" />
{locationLabel || messages.card.locationFallback}
</div>
{cinema.map_url ? (
<a
href={cinema.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"
>
{messages.detail.openMap}
<IconMap size={24} />
</a>
) : null}
</div>
{description ? (
<p className="text-xl leading-[1.3]">{description}</p>
) : null}
</div>
);
}
+73
View File
@@ -0,0 +1,73 @@
import { IconCircleCheck, IconExternalLink } from "@tabler/icons-react";
import type { Cinema, ContactChannel } from "@/lib/cinemas";
import { useI18n } from "@/lib/i18n";
import { translate } from "@/lib/i18n/messages";
import { COLORS } from "@/lib/design-tokens";
function isExternal(href: string | null): boolean {
return href !== null && href.startsWith("http");
}
function ContactRow({ channel }: { channel: ContactChannel }) {
return (
<div className="flex flex-col gap-2">
<span className="text-sm text-[#999]">{channel.label}</span>
<a
href={channel.href ?? undefined}
target={isExternal(channel.href) ? "_blank" : undefined}
rel="noreferrer"
className="flex items-center justify-between"
>
<span>{channel.value}</span>
<IconExternalLink size={16} />
</a>
</div>
);
}
/** กล่องติดต่อ/จองตั๋ว — แต่ละส่วนซ่อนได้ถ้ายังไม่มีข้อมูล */
export function ContactPanel({ cinema }: { cinema: Cinema }) {
const { messages } = useI18n();
return (
<aside
className="flex flex-col justify-between gap-6 rounded-xl p-6"
style={{ border: `1px solid ${COLORS.border}` }}
>
<div className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold leading-[1.3]">
{(cinema.contact_heading?.trim() || messages.detail.contactTitle)}
</h2>
{cinema.contacts.length === 0 ? (
<p className="text-sm text-[#999]">{messages.detail.contactsFallback}</p>
) : (
cinema.contacts.map((channel) => (
<ContactRow key={channel.label} channel={channel} />
))
)}
<div className="flex flex-col gap-3">
<span className="text-sm text-[#999]">
{messages.detail.paymentMethods}
</span>
{cinema.payments.length === 0 ? (
<span className="text-sm text-[#999]">
{messages.detail.paymentsFallback}
</span>
) : (
<div className="flex flex-wrap items-center gap-6">
{cinema.payments.map((payment) => (
<span key={payment} className="flex items-center gap-1 text-sm">
<IconCircleCheck size={16} />
{translate(messages.payments, payment)}
</span>
))}
</div>
)}
</div>
</div>
</aside>
);
}
@@ -0,0 +1,77 @@
import {
IconBook,
IconBriefcase,
IconCoffee,
IconPlant2,
IconShoppingBag,
IconSofa,
IconTicket,
IconToolsKitchen2,
type Icon as TablerIcon,
} from "@tabler/icons-react";
import { LocationPanel } from "@/components/cinema/LocationPanel";
import { cinemaFacilities, type Cinema } from "@/lib/cinemas";
import { useI18n } from "@/lib/i18n";
import type { FacilityKey } from "@/lib/i18n/messages";
import { COLORS } from "@/lib/design-tokens";
const FACILITY_ICONS: Record<FacilityKey, TablerIcon> = {
seating: IconSofa,
ticket: IconTicket,
restaurant: IconToolsKitchen2,
cafe: IconCoffee,
garden: IconPlant2,
bookstore: IconBook,
colearning: IconBriefcase,
other: IconShoppingBag,
};
/** สิ่งอำนวยความสะดวก (ซ้าย) + ที่ตั้ง (ขวา) ตาม layout ใน Figma */
export function FacilitiesSection({ cinema }: { cinema: Cinema }) {
const { locale, messages } = useI18n();
const facilities = cinemaFacilities(cinema);
return (
<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]">
{messages.detail.facilities}
</h2>
{facilities.length > 0 ? (
<div className="grid grid-cols-2 gap-x-4 gap-y-10 sm:grid-cols-4">
{facilities.map((key) => {
const Icon = FACILITY_ICONS[key];
const base = messages.facilities[key];
const custom = cinema.facility_details?.[key];
const title = custom?.label?.trim() || base.title;
// คำอธิบายแสดงเฉพาะที่กรอกไว้รายโรง (ค่าเริ่มต้นใช้เป็น placeholder ในหลังบ้าน)
const sub =
(locale === "en" ? custom?.sub_en : custom?.sub_th)?.trim() ?? "";
return (
<div key={key} className="flex flex-col items-center gap-3">
<div
className="flex size-[72px] items-center justify-center rounded-full"
style={{ background: COLORS.glowSoft }}
>
<Icon size={40} stroke={1.5} />
</div>
<div className="text-center">
<div className="font-medium">{title}</div>
{sub ? (
<div className="mt-1 text-sm text-[#B3B3B3]">{sub}</div>
) : null}
</div>
</div>
);
})}
</div>
) : (
<p className="text-sm text-[#777]">{messages.detail.noData}</p>
)}
</div>
<LocationPanel cinema={cinema} />
</section>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { IconChevronLeft, IconChevronRight } from "@tabler/icons-react";
import type { ReactNode } from "react";
import { Logo } from "@/components/site/Logo";
import { splitGallery } from "@/lib/gallery";
import { useI18n } from "@/lib/i18n";
type GalleryProps = {
photos: string[];
cinemaName: string;
};
type GallerySlotProps = {
photo: string | null;
alt: string;
/** เนื้อหาที่แสดงเมื่อยังไม่มีรูป — ใช้โลโก้ AlterFlixHub แทนข้อความ */
placeholder: ReactNode;
className: string;
};
function GallerySlot({ photo, alt, placeholder, className }: GallerySlotProps) {
if (!photo) {
return (
<div
className={`flex items-center justify-center bg-[#242424] text-sm text-[#999] ${className}`}
>
{placeholder}
</div>
);
}
return (
<img
src={photo}
alt={alt}
className={`bg-[#242424] object-cover ${className}`}
/>
);
}
/** แกลเลอรีภาพโรงหนัง — ป้าย "+N" คำนวณจากจำนวนรูปจริงในข้อมูล */
export function Gallery({ photos, cinemaName }: GalleryProps) {
const { messages } = useI18n();
const { main, thumbs, remaining } = splitGallery(photos);
const [firstThumb = null, secondThumb = null] = thumbs;
return (
<section className="grid gap-6 lg:grid-cols-[minmax(0,807px)_minmax(0,387px)]">
<div className="relative overflow-hidden rounded-xl">
<GallerySlot
photo={main}
alt={`${messages.gallery.main} — ${cinemaName}`}
placeholder={<Logo size="md" />}
className="aspect-[269/202] w-full lg:aspect-auto lg:h-[606px]"
/>
<button
type="button"
aria-label={messages.gallery.previous}
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
type="button"
aria-label={messages.gallery.next}
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="overflow-hidden rounded-xl">
<GallerySlot
photo={firstThumb}
alt={`${messages.gallery.second} — ${cinemaName}`}
placeholder={<Logo size="sm" />}
className="aspect-[387/290] w-full"
/>
</div>
<div className="relative overflow-hidden rounded-xl">
<GallerySlot
photo={secondThumb}
alt={`${messages.gallery.third} — ${cinemaName}`}
placeholder={<Logo size="sm" />}
className="aspect-[387/290] w-full"
/>
{remaining > 0 ? (
<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">
{messages.gallery.more(remaining)}
</div>
) : null}
</div>
</div>
</section>
);
}
+93
View File
@@ -0,0 +1,93 @@
import { IconMap } from "@tabler/icons-react";
import { COLORS } from "@/lib/design-tokens";
import { cinemaAddressLines, cinemaName, type Cinema } from "@/lib/cinemas";
import { useI18n } from "@/lib/i18n";
import { mapEmbedUrl, mapOpenUrl } from "@/lib/map-embed";
/**
* การ์ดที่ตั้ง + แผนที่
* แผนที่ดึงจากลิงก์ Google Maps ของโรง ถ้าไม่มีจึงใช้พิกัดที่กรอกในหลังบ้าน
* ถ้าไม่มีทั้งสองอย่างแสดง "ไม่มีข้อมูล"
*/
export function LocationPanel({ cinema }: { cinema: Cinema }) {
const { locale, messages } = useI18n();
const addressLines = cinemaAddressLines(cinema, locale);
const embedUrl = mapEmbedUrl(cinema, locale);
const openUrl = mapOpenUrl(cinema);
return (
<aside
className="flex flex-col gap-6 self-start rounded-xl p-6"
style={{ border: `1px solid ${COLORS.border}` }}
>
<div className="flex flex-col gap-4">
<div className="flex items-center justify-between gap-3">
<h2 className="text-2xl font-semibold leading-[1.3]">
{messages.detail.location}
</h2>
{openUrl ? (
<a
href={openUrl}
target="_blank"
rel="noreferrer"
className="inline-flex items-center gap-1 text-sm text-[#D47272] transition hover:text-white"
>
<IconMap size={16} />
{messages.detail.openMap}
</a>
) : null}
</div>
{embedUrl ? (
<div
className="relative h-[183px] overflow-hidden rounded-xl"
style={{
border: `1px solid ${COLORS.border}`,
background: COLORS.surfaceMuted,
}}
>
{/* ลายตารางใต้แผนที่ — กันช่องว่างขาวตอน iframe ยังโหลดไม่เสร็จ */}
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0"
style={{
backgroundImage:
"linear-gradient(rgba(255,255,255,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.05) 1px, transparent 1px)",
backgroundSize: "24px 24px",
}}
/>
<iframe
title={`${messages.detail.location} — ${cinemaName(cinema, locale)}`}
src={embedUrl}
loading="lazy"
referrerPolicy="no-referrer-when-downgrade"
allowFullScreen
className="relative size-full border-0"
/>
</div>
) : (
<div
className="flex h-[183px] items-center justify-center rounded-xl text-sm text-[#777]"
style={{
border: `1px dashed ${COLORS.border}`,
background: COLORS.surfaceMuted,
}}
>
{messages.detail.noData}
</div>
)}
</div>
<p className="text-sm leading-[1.3] text-[#999]">
{addressLines.length > 0
? addressLines.map((line) => (
<span key={line} className="block">
{line}
</span>
))
: messages.detail.addressFallback}
</p>
</aside>
);
}
+49
View File
@@ -0,0 +1,49 @@
import {
IconBus,
IconCar,
IconTrain,
type Icon as TablerIcon,
} from "@tabler/icons-react";
import { transportValue, type TransportMode } from "@/lib/cinemas";
import { useI18n } from "@/lib/i18n";
import { COLORS } from "@/lib/design-tokens";
const TRANSPORT_ICONS: Record<TransportMode["icon_name"], TablerIcon> = {
private_car: IconCar,
metro: IconTrain,
bus: IconBus,
};
/** วิธีเดินทางมาถึงโรงหนัง — ซ่อนทั้งบล็อกถ้ายังไม่มีข้อมูล */
export function TransportList({ transport }: { transport: TransportMode[] }) {
const { locale, messages } = useI18n();
// แถวที่ยังไม่ได้กรอกรายละเอียด (เพิ่มจากหลังบ้านแล้วเว้นว่าง) ไม่ต้องแสดง
const routes = transport.filter((route) => route.value.trim() !== "");
if (routes.length === 0) return null;
return (
<div className="flex flex-col">
{routes.map((route, index) => {
const Icon = TRANSPORT_ICONS[route.icon_name];
const isLast = index === routes.length - 1;
return (
<div
key={`${route.icon_name}-${index}`}
className="flex flex-col justify-between gap-1 py-2.5 sm:min-h-10 sm:flex-row sm:gap-4"
style={{
borderBottom: isLast ? undefined : `1px solid ${COLORS.border}`,
}}
>
<div className="flex items-center gap-2 font-medium">
<Icon size={20} />
{messages.transport[route.icon_name]}
</div>
<div className="sm:text-right">{transportValue(route, locale)}</div>
</div>
);
})}
</div>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { IconCircleCheck, IconMapPin, IconSearch } from "@tabler/icons-react";
import type { NearMeStatus } from "@/hooks/use-near-me";
import { useI18n } from "@/lib/i18n";
type HeroSectionProps = {
query: string;
onQueryChange: (query: string) => void;
nearMeStatus: NearMeStatus;
onRequestLocation: () => void;
};
/** ข้อความสถานะของปุ่ม "ใกล้ฉัน" — แสดงเฉพาะตอนกำลังหา/ผิดพลาด/พร้อมใช้ */
function statusMessage(status: NearMeStatus, messages: ReturnType<typeof useI18n>["messages"]) {
switch (status) {
case "locating":
return messages.search.locating;
case "denied":
return messages.search.denied;
case "unsupported":
return messages.search.unsupported;
case "error":
return messages.search.error;
case "ready":
return messages.search.sortedByDistance;
default:
return null;
}
}
/** ฮีโร่หน้าแรก: หัวข้อ + ช่องค้นหา (ค้นทันทีขณะพิมพ์) + ปุ่มหาตำแหน่ง */
export function HeroSection({
query,
onQueryChange,
nearMeStatus,
onRequestLocation,
}: HeroSectionProps) {
const { messages } = useI18n();
const status = statusMessage(nearMeStatus, messages);
const isReady = nearMeStatus === "ready";
return (
<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]">
{messages.hero.titlePrefix}
<span className="text-[#A92626]">{messages.hero.titleHighlight}</span>
{messages.hero.titleSuffix}
</h1>
<p className="text-base md:text-xl">{messages.hero.subtitle}</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
value={query}
onChange={(event) => onQueryChange(event.target.value)}
placeholder={messages.search.placeholder}
aria-label={messages.search.placeholder}
className="min-w-0 flex-1 bg-transparent text-sm text-white outline-none placeholder:text-[#454545]"
/>
<button
type="button"
onClick={onRequestLocation}
disabled={nearMeStatus === "locating"}
aria-label={messages.search.nearMe}
className={`hidden items-center gap-2 border-l border-[#999] px-4 text-sm transition disabled:opacity-60 sm:flex ${
isReady ? "text-[#D47272]" : "text-[#999] hover:text-white"
}`}
>
{isReady ? <IconCircleCheck size={16} /> : <IconMapPin size={16} />}
{messages.search.nearMe}
</button>
<button
type="button"
className="h-8 rounded-lg border border-[#8F0808] bg-[#8F0808] px-6 text-sm font-medium transition hover:bg-[#a30a0a]"
>
{messages.search.submit}
</button>
</div>
{status ? (
<p
role="status"
aria-live="polite"
className={`px-1 pt-3 text-xs ${
nearMeStatus === "ready" ? "text-[#B3B3B3]" : "text-[#D47272]"
}`}
>
{status}
</p>
) : null}
</div>
</section>
);
}
+28
View File
@@ -0,0 +1,28 @@
import { HeaderActionsProvider } from "@agent-native/toolkit/app-shell";
interface LayoutProps {
children: React.ReactNode;
}
/**
* Clean Agent-Native app shell: a single full-height canvas with no chat or
* agent UI mounted by default. The app already satisfies the Agent-Native
* contract (data in SQL, actions as the source of truth, application state for
* navigation, real-time sync) — the agent rail and chat are opt-in surfaces.
*
* To add the persistent agent rail when the user asks for it, wrap {children}
* in `AgentSidebar` from "@agent-native/core/client/agent-chat"
* (position="right", a stable storageKey, browserTabId={TAB_ID} from
* "@/lib/tab-id"). See the `agent-native-toolkit` skill for the full pattern.
*/
export function Layout({ children }: LayoutProps) {
return (
<HeaderActionsProvider>
<div className="flex h-screen w-full flex-col overflow-hidden bg-background text-foreground">
<main className="agent-native-app-main min-w-0 flex-1 overflow-y-auto overscroll-contain">
{children}
</main>
</div>
</HeaderActionsProvider>
);
}
+98
View File
@@ -0,0 +1,98 @@
import {
IconArrowRight,
IconBuildingCommunity,
IconMapPin,
} from "@tabler/icons-react";
import { Link } from "react-router";
import {
CARD_GRADIENTS,
cinemaCategoryLabel,
cinemaLocationLabel,
cinemaName,
type Cinema,
} from "@/lib/cinemas";
import { formatDistance } from "@/lib/geo";
import { trackEvent } from "@/lib/analytics-client";
import { useNearMe } from "@/hooks/use-near-me";
import { useI18n } from "@/lib/i18n";
type CinemaCardProps = {
cinema: Cinema;
/** ลำดับการ์ด ใช้เลือก gradient ให้สลับสีสม่ำเสมอ */
index?: number;
/** ที่มาของการ์ด ใช้บันทึกสถิติการคลิก */
source?: string;
/** คำค้นปัจจุบัน (แนบไปกับการคลิกเพื่อวัด CTR ของคำค้น) */
searchQuery?: string;
};
export function CinemaCard({
cinema,
index = 0,
source = "list",
searchQuery,
}: CinemaCardProps) {
const { locale, messages } = useI18n();
const { distances } = useNearMe();
const gradient = CARD_GRADIENTS[index % CARD_GRADIENTS.length];
// รูปแรก = ปกการ์ด (ถ้าไม่มีรูป ใช้ gradient เดิมเป็นพื้นหลัง)
const cover = cinema.photos.find((photo) => photo.trim() !== "");
const distanceLabel = formatDistance(
distances[cinema.slug],
messages.card.distanceFallback,
);
return (
<article
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] ${gradient}`}
>
{cover ? (
<>
<img
src={cover}
alt=""
aria-hidden="true"
loading="lazy"
className="absolute inset-0 size-full object-cover"
/>
{/* ไล่เงาเพื่อให้ตัวอักษรบนการ์ดอ่านได้ */}
<div
aria-hidden="true"
className="absolute inset-0 bg-gradient-to-t from-[#0D0D0D]/95 via-[#0D0D0D]/35 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]">{distanceLabel}</span>
<h3 className="text-sm font-semibold">{cinemaName(cinema, locale)}</h3>
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
<IconMapPin size={12} />
{cinemaLocationLabel(cinema, locale) || messages.card.locationFallback}
</p>
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
<IconBuildingCommunity size={12} />
{cinemaCategoryLabel(cinema, messages) ||
messages.card.categoryFallback}
</p>
<Link
to={`/cinema/${cinema.slug}`}
onClick={() =>
trackEvent({
type: "cinema_select",
slug: cinema.slug,
source,
query: searchQuery,
position: index + 1,
locale,
})
}
className="mt-3 flex items-center justify-end gap-2 text-xs font-medium"
>
{messages.card.seeDetail} <IconArrowRight size={12} />
</Link>
</div>
</article>
);
}
+66
View File
@@ -0,0 +1,66 @@
import { CinemaCard } from "@/components/site/CinemaCard";
import type { Cinema, CinemaCategory } from "@/lib/cinemas";
import { useI18n } from "@/lib/i18n";
/** กริดการ์ดโรงหนัง — ใช้ทั้งหน้าแรกและส่วน "โรงหนังอิสระอื่นๆ" */
export function CinemaGrid({
cinemas,
source = "list",
searchQuery,
}: {
cinemas: Cinema[];
source?: string;
searchQuery?: string;
}) {
return (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
{cinemas.map((cinema, index) => (
<CinemaCard
key={cinema.slug}
cinema={cinema}
index={index}
source={source}
searchQuery={searchQuery}
/>
))}
</div>
);
}
type CategoryFilterProps = {
/** เก็บคีย์หมวดเป็นภาษาไทยเสมอ เพื่อใช้กรองข้อมูลได้ทุกภาษา */
active: CinemaCategory;
categories: readonly CinemaCategory[];
onChange: (category: CinemaCategory) => void;
};
export function CategoryFilter({
active,
categories,
onChange,
}: CategoryFilterProps) {
const { messages } = useI18n();
return (
<div className="flex flex-wrap gap-2">
{categories.map((category) => {
const isActive = category === active;
return (
<button
key={category}
type="button"
onClick={() => onChange(category)}
aria-pressed={isActive}
className={
isActive
? "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"
}
>
{messages.categories[category]}
</button>
);
})}
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
import { useI18n } from "@/lib/i18n";
import { LOCALE_OPTIONS } from "@/lib/i18n/messages";
import { COLORS } from "@/lib/design-tokens";
/** ธงชาติไทยย่อส่วน */
function FlagTh() {
return (
<span
className="block h-4 w-[21px] shrink-0 rounded-[1px]"
style={{ background: COLORS.flagGradient }}
/>
);
}
/** ธงสหราชอาณาจักรย่อส่วน */
function FlagEn() {
return (
<span
className="relative block h-4 w-[21px] shrink-0 overflow-hidden rounded-[1px]"
style={{ background: "#012169" }}
>
<span
className="absolute inset-0"
style={{
background:
"linear-gradient(45deg, transparent 44%, #F4F5F8 44% 56%, transparent 56%), linear-gradient(-45deg, transparent 44%, #F4F5F8 44% 56%, transparent 56%)",
}}
/>
<span
className="absolute inset-0"
style={{
background:
"linear-gradient(90deg, transparent 40%, #F4F5F8 40% 60%, transparent 60%), linear-gradient(0deg, transparent 33%, #F4F5F8 33% 67%, transparent 67%)",
}}
/>
<span
className="absolute inset-0"
style={{
background:
"linear-gradient(90deg, transparent 44%, #C8102E 44% 56%, transparent 56%), linear-gradient(0deg, transparent 40%, #C8102E 40% 60%, transparent 60%)",
}}
/>
</span>
);
}
const FLAGS = { th: FlagTh, en: FlagEn } as const;
/**
* สลับภาษาเป็นปุ่มสองปุ่ม (TH / EN) — ไม่มีเมนูให้เปิด/ปิด
* จึงไม่มีปัญหาคลิกพลาดหรือเมนูถูกบัง และกดครั้งเดียวเปลี่ยนทันที
*/
export function LocaleSwitcher() {
const { locale, setLocale } = useI18n();
return (
<div role="group" aria-label="ภาษา" className="flex items-center gap-1">
{LOCALE_OPTIONS.map((option) => {
const Flag = FLAGS[option.locale];
const isActive = option.locale === locale;
return (
<button
key={option.locale}
type="button"
lang={option.locale}
onClick={() => setLocale(option.locale)}
aria-pressed={isActive}
title={option.name}
className={`flex items-center gap-1.5 rounded-lg px-1.5 py-1 text-sm transition sm:gap-2 sm:px-2 ${
isActive
? "bg-[#242424] font-semibold text-[#D47272]"
: "text-[#B3B3B3] hover:text-white"
}`}
>
<span className="hidden sm:block">
<Flag />
</span>
<span className="text-base font-medium leading-none sm:text-lg">
{option.code}
</span>
</button>
);
})}
</div>
);
}
+35
View File
@@ -0,0 +1,35 @@
import { describe, expect, it } from "vitest";
import { LOGO_SPEC } from "@/lib/design-tokens";
import { logoClasses } from "@/components/site/Logo";
/**
* กันการเผลอเปลี่ยนโลโก้: สเปกใน DESIGN.md ถูกตรึงไว้ที่นี่
* ถ้าเทสต์นี้พัง แปลว่ามีคนแก้สเปกโลโก้ — ต้องขออนุมัติก่อน
*/
describe("โลโก้ AlterFlixHub (สเปกที่ห้ามเปลี่ยน)", () => {
it("ใช้คำว่า AlterFlixHub เท่านั้น", () => {
expect(LOGO_SPEC.wordmark).toBe("AlterFlixHub");
});
it("ฟอนต์ต้องเป็น Jersey 15", () => {
expect(LOGO_SPEC.fontFamily).toContain("Jersey 15");
expect(logoClasses("md")).toContain("font-['Jersey_15']");
expect(logoClasses("sm")).toContain("font-['Jersey_15']");
});
it("สีต้องเป็นแดงแบรนด์ #8F0808", () => {
expect(LOGO_SPEC.color).toBe("#8F0808");
});
it("header 36px (md) และ footer 24px (sm) เท่านั้น", () => {
expect(LOGO_SPEC.sizes.md).toBe("text-4xl");
expect(LOGO_SPEC.sizes.sm).toBe("text-2xl");
expect(logoClasses("md")).toContain("text-4xl");
expect(logoClasses("sm")).toContain("text-2xl");
});
it("ไม่มีตัวเลือกขนาดอื่นนอกเหนือจาก sm/md", () => {
expect(Object.keys(LOGO_SPEC.sizes).sort()).toEqual(["md", "sm"]);
});
});
+26
View File
@@ -0,0 +1,26 @@
import { LOGO_SPEC, type LogoSize } from "@/lib/design-tokens";
type LogoProps = {
className?: string;
/** sm = footer (24px) · md = header (36px) */
size?: LogoSize;
};
/**
* โลโก้ AlterFlixHub — ตาม DESIGN.md หัวข้อ "โลโก้ (ห้ามเปลี่ยนแปลง)"
* ฟอนต์ Jersey 15 สี #8F0808 และมีสองขนาดเท่านั้น (sm/md)
*/
export function logoClasses(size: LogoSize = "md"): string {
return `font-['Jersey_15'] leading-none ${LOGO_SPEC.sizes[size]}`;
}
export function Logo({ className = "", size = "md" }: LogoProps) {
return (
<span
className={`${logoClasses(size)} ${className}`}
style={{ fontFamily: LOGO_SPEC.fontFamily, color: LOGO_SPEC.color }}
>
{LOGO_SPEC.wordmark}
</span>
);
}
+55
View File
@@ -0,0 +1,55 @@
import { Link } from "react-router";
import { Logo } from "@/components/site/Logo";
import { footerIcon } from "@/components/site/footer-icons";
import { useContent } from "@/lib/content-context";
import { useI18n } from "@/lib/i18n";
/**
* Footer ใช้คอนเทนเนอร์เดียวกับ <main> ของทุกหน้า (max-w-[1440px] + px เดียวกัน)
* ขอบซ้าย/ขวาจึงตรงกับกริดการ์ดโรงหนังเป๊ะ ไม่ว่าหน้าจะแสดงการ์ดกี่ใบ
*/
export function SiteFooter() {
const { site } = useContent();
const { messages } = useI18n();
return (
<footer className="relative z-10 mx-auto w-full max-w-[1440px] px-5 pb-6 md:px-[108px]">
<div className="flex flex-col items-center gap-3 border-t border-white/10 pt-4 sm:flex-row sm:justify-between">
<div className="flex items-center gap-4">
<Logo size="sm" />
<nav aria-label="เมนูล่าง" className="flex items-center gap-3 text-xs">
<Link
to="/about"
className="text-[#B3B3B3] transition hover:text-white"
>
{messages.nav.about}
</Link>
</nav>
</div>
<div className="flex flex-wrap items-center justify-center gap-1.5">
{site.footer.map((item) => {
const Icon = footerIcon(item.icon_name);
const isExternal = item.href.startsWith("http");
return (
<a
key={item.id}
href={item.href || "#"}
aria-label={item.label}
title={item.label}
target={isExternal ? "_blank" : undefined}
rel={isExternal ? "noreferrer" : undefined}
className="flex size-8 items-center justify-center rounded-full bg-white/90 text-[#0D0D0D] transition hover:bg-white"
>
<Icon size={18} />
</a>
);
})}
</div>
<p className="text-xs text-[#999]">Copyright © AlterFlixHub</p>
</div>
</footer>
);
}
+39
View File
@@ -0,0 +1,39 @@
import { Link, useLocation } from "react-router";
import { Logo } from "@/components/site/Logo";
import { LocaleSwitcher } from "@/components/site/LocaleSwitcher";
import { useI18n } from "@/lib/i18n";
/**
* Header: โลโก้ชิดซ้าย · ด้านขวาเป็น [เกี่ยวกับเรา] + [ปุ่มภาษา TH/EN]
* ไม่มีเมนู "หน้าแรก" — กลับหน้าแรกได้ด้วยการกดโลโก้
*/
export function SiteHeader() {
const { messages } = useI18n();
const { pathname } = useLocation();
const isAbout = pathname.startsWith("/about");
return (
<header className="relative z-10 mx-auto flex h-[68px] w-full max-w-[1440px] items-center justify-between gap-4 px-5 md:px-[108px]">
<Link to="/" aria-label={`AlterFlixHub — ${messages.nav.home}`} className="shrink-0">
<Logo />
</Link>
<div className="flex items-center gap-1.5 sm:gap-2">
<Link
to="/about"
aria-current={isAbout ? "page" : undefined}
className={`rounded-lg border px-2 py-1 text-xs transition sm:px-3 sm:py-1.5 sm:text-sm ${
isAbout
? "border-[#A92626] bg-[#8F0808]/20 text-white"
: "border-[#303030] text-[#B3B3B3] hover:border-[#A92626]/60 hover:text-white"
}`}
>
{messages.nav.about}
</Link>
<LocaleSwitcher />
</div>
</header>
);
}
+73
View File
@@ -0,0 +1,73 @@
import type { ReactNode } from "react";
import { SiteFooter } from "@/components/site/SiteFooter";
import { SiteHeader } from "@/components/site/SiteHeader";
type ShellVariant = "home" | "detail";
const HERO_IMAGE = "/images/hero.png";
/**
* กรอบของตกแต่งพื้นหลัง
* ต้องมี overflow-hidden ไม่งั้น glow ที่วางด้วย top/bottom แบบ px
* จะยืด scrollHeight ของหน้าให้ยาวเกินเนื้อหา → เกิดพื้นที่ว่างใต้ footer
*/
function BackdropFrame({ children }: { children: ReactNode }) {
return (
<div
aria-hidden="true"
className="pointer-events-none absolute inset-0 overflow-hidden"
>
{children}
</div>
);
}
/** พื้นหลังหน้าแรก: รูปฮีโร่ + ไล่สีลงพื้นหลัง + แสงแดงสองจุด */
function HomeBackdrop() {
return (
<BackdropFrame>
<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]" />
{/* จุดล่างยึดกับขอบล่างของหน้า (เดิมใช้ top-[1620px] ตายตัว จึงล้นเลย footer เมื่อแสดงโรงหนังแบบย่อ) */}
<div className="pointer-events-none absolute bottom-[-140px] left-1/2 size-[382px] -translate-x-1/2 rounded-full bg-[#4C0404]/70 blur-[237px]" />
</BackdropFrame>
);
}
/** พื้นหลังหน้ารายละเอียด: แสงแดงจุดเดียวตามระยะใน Figma */
function DetailBackdrop() {
return (
<BackdropFrame>
<div className="pointer-events-none absolute left-1/2 top-[649px] size-[382px] -translate-x-1/2 rounded-full bg-[#4C0404] opacity-[0.66] blur-[237px]" />
</BackdropFrame>
);
}
/**
* โครงหน้าเว็บที่ทุก route ใช้ร่วมกัน (พื้นหลัง + header + footer)
* variant เลือกชุดพื้นหลัง ไม่ใช่ layout — เนื้อหายังคงอยู่ใน route
*/
export function SiteShell({
variant,
children,
}: {
variant: ShellVariant;
children: ReactNode;
}) {
return (
<div className="relative flex min-h-dvh w-full flex-col overflow-x-hidden bg-[#0D0D0D] text-white">
{variant === "home" ? <HomeBackdrop /> : <DetailBackdrop />}
<SiteHeader />
{/* flex-1 ดัน footer ไปท้ายจอเมื่อเนื้อหาสั้น — เป็น block ธรรมดา
(ไม่ใช้ flex-col เพื่อไม่ให้ main ที่มี mx-auto หดเหลือ max-content จนล้นจอมือถือ) */}
<div className="flex-1">{children}</div>
<SiteFooter />
</div>
);
}
+33
View File
@@ -0,0 +1,33 @@
import {
IconBrandFacebook,
IconBrandInstagram,
IconBrandLinkedin,
IconBrandTelegram,
IconBrandTiktok,
IconBrandX,
IconBrandYoutube,
IconLink,
IconMail,
IconPhone,
type Icon as TablerIcon,
} from "@tabler/icons-react";
/** ไอคอนที่เลือกใช้ได้ใน footer — เพิ่มชื่อใหม่ได้โดยเติมใน map นี้ */
export const FOOTER_ICONS: Record<string, TablerIcon> = {
IconBrandFacebook,
IconBrandInstagram,
IconBrandLinkedin,
IconBrandYoutube,
IconBrandTelegram,
IconBrandTiktok,
IconBrandX,
IconMail,
IconPhone,
IconLink,
};
export const FOOTER_ICON_NAMES = Object.keys(FOOTER_ICONS);
export function footerIcon(name: string): TablerIcon {
return FOOTER_ICONS[name] ?? IconLink;
}
+1
View File
@@ -0,0 +1 @@
export * from "@agent-native/toolkit/ui/button";
+20
View File
@@ -0,0 +1,20 @@
import {
ToolkitProvider,
type ToolkitComponents,
} from "@agent-native/toolkit/provider";
import type { ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { designSystem } from "@/design-system";
const components: ToolkitComponents = {
Button: Button as ToolkitComponents["Button"],
};
export function AppToolkitProvider({ children }: { children: ReactNode }) {
return (
<ToolkitProvider components={components} designSystem={designSystem}>
{children}
</ToolkitProvider>
);
}
+3
View File
@@ -0,0 +1,3 @@
import { defineDesignSystem } from "@agent-native/toolkit/design-system";
export const designSystem = defineDesignSystem({});
+10
View File
@@ -0,0 +1,10 @@
import { configureClientRouterBasename } from "@agent-native/core/client/api-path";
import { installRouteChunkRecovery } from "@agent-native/core/client/route-chunk-recovery";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";
installRouteChunkRecovery();
configureClientRouterBasename();
hydrateRoot(document, <HydratedRouter />);
+10
View File
@@ -0,0 +1,10 @@
import {
createDocumentRequestHandler,
streamTimeout,
} from "@agent-native/core/server/entry-server";
import { ServerRouter } from "react-router";
const handleDocumentRequest = createDocumentRequestHandler(ServerRouter);
export { streamTimeout };
export default handleDocumentRequest;
+263
View File
@@ -0,0 +1,263 @@
@import url("https://fonts.googleapis.com/css2?family=Jersey+15&family=Noto+Sans+Thai:wght@400;500;600;700&display=swap");
@import "@fontsource-variable/inter";
@import "@fontsource/ibm-plex-sans-thai-looped/400.css";
@import "@fontsource/ibm-plex-sans-thai-looped/500.css";
@import "tailwindcss";
@import "@agent-native/toolkit/styles.css";
@source "./**/*.{ts,tsx}";
/* ฟอนต์เนื้อหายาว (มีหัว) — หัวข้อและ UI ยังใช้ Inter + Noto Sans Thai ตาม DESIGN.md */
@theme {
--font-content: "IBM Plex Sans Thai Looped", "Noto Sans Thai", sans-serif;
}
:root {
--background: 0 0% 100%;
--foreground: 0 0% 10%;
--card: 0 0% 100%;
--card-foreground: 0 0% 10%;
--popover: 0 0% 100%;
--popover-foreground: 0 0% 10%;
--primary: 0 0% 15%;
--primary-foreground: 0 0% 100%;
--secondary: 0 0% 95%;
--secondary-foreground: 0 0% 15%;
--muted: 0 0% 95%;
--muted-foreground: 0 0% 45%;
--accent: 0 0% 95%;
--accent-foreground: 0 0% 15%;
--destructive: 0 91% 71%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 90%;
--input: 0 0% 90%;
--ring: 0 0% 40%;
--radius: 0.5rem;
--sidebar-background: 0 0% 97%;
--sidebar-foreground: 0 0% 45%;
--sidebar-primary: 0 0% 15%;
--sidebar-primary-foreground: 0 0% 100%;
--sidebar-accent: 0 0% 95%;
--sidebar-accent-foreground: 0 0% 15%;
--sidebar-border: 0 0% 90%;
--sidebar-ring: 0 0% 40%;
--chat-sidebar-width: 17.25rem;
--chat-sidebar-content-inset: 0.5rem;
--chat-sidebar-row-padding: 0.75rem;
--chat-sidebar-title-fade: 1.25rem;
}
.chat-layout-shell {
--agent-layout-left-drawer-expanded-width: var(--chat-sidebar-width);
--agent-native-lower-surface: var(--agent-kit-nav-surface);
}
.agentkit-chat-empty-copy {
text-align: center;
}
.agentkit-chat-empty-copy h1 {
margin: 0;
color: hsl(var(--foreground));
font-size: 1.5rem;
font-weight: 600;
letter-spacing: -0.02em;
}
.agent-kit-chat-footer-stack {
inline-size: min(100%, 47rem);
margin-inline: auto;
pointer-events: auto;
}
.agent-kit-chat-footer-stack > .agentkit-composer-stack {
inline-size: 100%;
}
.agent-kit-chat-guided-question {
max-block-size: min(32rem, 58dvh);
overflow: auto;
margin-block-end: 0.5rem;
border: 1px solid var(--agentkit-border);
border-radius: var(--agentkit-radius);
background: var(--agentkit-surface);
box-shadow: var(--agentkit-elevation);
}
.chat-sidebar-history .an-chat-history__list {
padding-top: 0;
}
.chat-sidebar-history .an-chat-history__section-label {
padding: 8px
calc(var(--chat-sidebar-content-inset) + var(--chat-sidebar-row-padding))
5px;
color: hsl(var(--sidebar-foreground) / 0.66);
font-size: 11px;
font-weight: 500;
letter-spacing: 0;
text-transform: none;
}
.chat-sidebar-history.an-chat-history--rail .an-chat-history-row {
margin-inline: var(--chat-sidebar-content-inset);
border-radius: calc(var(--radius) + 2px);
}
.chat-sidebar-history.an-chat-history--rail .an-chat-history-row__button {
min-height: 34px;
padding-block: 7px;
padding-inline: var(--chat-sidebar-row-padding);
color: hsl(var(--sidebar-foreground));
}
.chat-sidebar-history.an-chat-history--rail
.an-chat-history-row--has-menu
.an-chat-history-row__button {
padding-inline-end: calc(var(--chat-sidebar-row-padding) + 1.5rem);
}
.chat-sidebar-history .an-chat-history-row__title {
flex: 1 1 auto;
color: hsl(var(--sidebar-accent-foreground));
font-size: 13px;
font-weight: 400;
text-overflow: clip;
}
.chat-sidebar-thread-title-shell {
display: flex;
min-width: 0;
align-items: center;
gap: 6px;
}
.chat-sidebar-thread-title {
display: block;
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
white-space: nowrap;
}
.chat-sidebar-thread-running {
color: hsl(var(--sidebar-foreground) / 0.72);
}
.chat-sidebar-thread-title[data-overflow="true"] {
mask-image: linear-gradient(
to right,
hsl(var(--foreground)) 0,
hsl(var(--foreground)) calc(100% - var(--chat-sidebar-title-fade)),
hsl(var(--foreground) / 0) 100%
);
}
.chat-sidebar-thread-title__content {
display: block;
width: max-content;
transform: translateX(0);
}
.an-chat-history-row:hover
.chat-sidebar-thread-title[data-overflow="true"]
.chat-sidebar-thread-title__content {
animation: chat-sidebar-title-reveal
var(--chat-sidebar-title-duration, 1800ms) ease-in-out 350ms;
}
.chat-sidebar-thread-details {
border-color: hsl(var(--sidebar-border));
}
.chat-sidebar-history.an-chat-history--rail
.an-chat-history-row__menu-trigger--pinned {
pointer-events: none;
opacity: 0;
}
.chat-sidebar-history.an-chat-history--rail
.an-chat-history-row:hover
.an-chat-history-row__menu-trigger--pinned,
.chat-sidebar-history.an-chat-history--rail
.an-chat-history-row:focus-within
.an-chat-history-row__menu-trigger--pinned,
.chat-sidebar-history.an-chat-history--rail
.an-chat-history-row__menu-trigger--pinned[aria-expanded="true"] {
pointer-events: auto;
opacity: 1;
}
@keyframes chat-sidebar-title-reveal {
to {
transform: translateX(calc(-1 * var(--chat-sidebar-title-shift, 0px)));
}
}
@media (prefers-reduced-motion: reduce) {
.an-chat-history-row:hover .chat-sidebar-thread-title__content {
animation: none;
}
}
.chat-sidebar-history.an-chat-history--rail
.an-chat-history-row--active
.an-chat-history-row__button {
background: hsl(var(--sidebar-accent));
color: hsl(var(--sidebar-accent-foreground));
}
.dark {
--background: 0 0% 13%;
--foreground: 0 0% 90%;
--card: 0 0% 16.47%;
--card-foreground: 0 0% 90%;
--popover: 0 0% 15%;
--popover-foreground: 0 0% 90%;
--primary: 0 0% 75%;
--primary-foreground: 0 0% 10%;
--secondary: 0 0% 18%;
--secondary-foreground: 0 0% 90%;
--muted: 0 0% 16%;
--muted-foreground: 0 0% 60%;
--accent: 0 0% 18%;
--accent-foreground: 0 0% 90%;
--destructive: 0 84% 60%;
--destructive-foreground: 0 0% 98%;
--border: 0 0% 24%;
--input: 0 0% 24%;
--ring: 0 0% 60%;
--radius: 0.5rem;
--sidebar-background: 0 0% 10%;
--sidebar-foreground: 0 0% 60%;
--sidebar-primary: 0 0% 75%;
--sidebar-primary-foreground: 0 0% 10%;
--sidebar-accent: 0 0% 16%;
--sidebar-accent-foreground: 0 0% 90%;
--sidebar-border: 0 0% 20%;
--sidebar-ring: 0 0% 60%;
}
@layer base {
body {
@apply bg-background text-foreground;
font-family: "Inter Variable", "Inter", "Noto Sans Thai", sans-serif;
font-feature-settings: "cv02", "cv03", "cv04", "cv11";
}
}
::-webkit-scrollbar {
width: 5px;
height: 5px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: hsl(var(--muted-foreground) / 0.22);
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: hsl(var(--muted-foreground) / 0.34);
}
+73
View File
@@ -0,0 +1,73 @@
import {
appBasePath,
appPathFromLocalRoute,
} from "@agent-native/core/client/api-path";
import { useAgentRouteState } from "@agent-native/core/client/navigation";
import { TAB_ID } from "@/lib/tab-id";
export interface NavigationState {
view?: string;
path?: string;
publicPath?: string;
}
export function useNavigationState() {
useAgentRouteState<NavigationState>({
browserTabId: TAB_ID,
requestSource: TAB_ID,
getNavigationState: ({ pathname }) => ({
view: viewForPath(pathname),
path: pathname,
publicPath: appPathFromLocalRoute(pathname),
}),
getCommandPath: commandPathForNavigation,
});
}
export function commandPathForNavigation(command: NavigationState): string {
const fallbackPath = pathForView(command?.view);
const path = typeof command?.path === "string" ? command.path : "";
if (!path) return fallbackPath;
const basePath = appBasePath();
if (!basePath) return path;
const suffixIndex = path.search(/[?#]/);
const pathname = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
const suffix = suffixIndex === -1 ? "" : path.slice(suffixIndex);
const publicPath =
typeof command?.publicPath === "string" ? command.publicPath : "";
const publicPathSuffixIndex = publicPath.search(/[?#]/);
const declaredPublicPath =
publicPathSuffixIndex === -1
? publicPath
: publicPath.slice(0, publicPathSuffixIndex);
const publicViewPath = appPathFromLocalRoute(pathForView(command?.view));
if (
matchesPathPrefix(pathname, basePath) &&
(matchesPathPrefix(pathname, publicViewPath) ||
(declaredPublicPath && declaredPublicPath === pathname))
) {
return `${pathname.slice(basePath.length) || "/"}${suffix}`;
}
return path;
}
function matchesPathPrefix(pathname: string, prefix: string): boolean {
return pathname === prefix || pathname.startsWith(`${prefix}/`);
}
function viewForPath(pathname: string): string {
if (pathname === "/") return "home";
return "home";
}
function pathForView(view?: string): string {
switch (view) {
case "home":
return "/";
default:
return "/";
}
}
+124
View File
@@ -0,0 +1,124 @@
import {
createContext,
useCallback,
useContext,
useMemo,
useState,
type ReactNode,
} from "react";
import { CINEMAS, type Cinema } from "@/lib/cinemas";
import {
fetchRoadDistances,
straightLineDistance,
type Coordinates,
type DistanceResult,
} from "@/lib/geo";
export type NearMeStatus =
| "idle"
| "locating"
| "ready"
| "denied"
| "unsupported"
| "error";
export type NearMeContextValue = {
status: NearMeStatus;
coords: Coordinates | null;
/** ระยะทางต่อ slug — มีค่าเฉพาะหลังขอตำแหน่งสำเร็จ */
distances: Record<string, DistanceResult | undefined>;
requestLocation: () => void;
};
const GEOLOCATION_TIMEOUT_MS = 10000;
const NearMeContext = createContext<NearMeContextValue | null>(null);
/** คำนวณระยะทางเส้นตรงให้ทุกโรง (ใช้เมื่อ OSRM เรียกไม่สำเร็จ) */
function straightLineDistances(cinemas: Cinema[], origin: Coordinates) {
const result: Record<string, DistanceResult | undefined> = {};
for (const cinema of cinemas) {
if (!cinema.coordinates) continue;
result[cinema.slug] = straightLineDistance(origin, cinema.coordinates);
}
return result;
}
/**
* แชร์ตำแหน่งอุปกรณ์และระยะทางถึงแต่ละโรงให้ทุกหน้า
* ขอตำแหน่งเฉพาะเมื่อผู้ใช้กด "ใกล้ฉัน" เท่านั้น (ไม่ขออัตโนมัติ)
* รายการโรงหนังมาจากเนื้อหาที่โหลดใน root loader (แก้จากหลังบ้านได้)
*/
export function NearMeProvider({
cinemas,
children,
}: {
cinemas: Cinema[];
children: ReactNode;
}) {
const [status, setStatus] = useState<NearMeStatus>("idle");
const [coords, setCoords] = useState<Coordinates | null>(null);
const [distances, setDistances] = useState<
Record<string, DistanceResult | undefined>
>({});
const loadDistances = useCallback(
async (origin: Coordinates) => {
const targets = cinemas.filter((cinema) => cinema.coordinates !== null);
try {
const road = await fetchRoadDistances(
origin,
targets.map((cinema) => cinema.coordinates as Coordinates),
);
const next: Record<string, DistanceResult | undefined> = {};
targets.forEach((cinema, index) => {
const destination = cinema.coordinates as Coordinates;
next[cinema.slug] =
road[index] ?? straightLineDistance(origin, destination);
});
setDistances(next);
} catch {
setDistances(straightLineDistances(cinemas, origin));
}
setStatus("ready");
},
[cinemas],
);
const requestLocation = useCallback(() => {
if (typeof navigator === "undefined" || !navigator.geolocation) {
setStatus("unsupported");
return;
}
setStatus("locating");
navigator.geolocation.getCurrentPosition(
(position) => {
const origin: Coordinates = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
};
setCoords(origin);
void loadDistances(origin);
},
(error) => {
setStatus(error.code === error.PERMISSION_DENIED ? "denied" : "error");
},
{ timeout: GEOLOCATION_TIMEOUT_MS, maximumAge: 60000 },
);
}, [loadDistances]);
const value = useMemo<NearMeContextValue>(
() => ({ status, coords, distances, requestLocation }),
[status, coords, distances, requestLocation],
);
return <NearMeContext.Provider value={value}>{children}</NearMeContext.Provider>;
}
export function useNearMe(): NearMeContextValue {
const value = useContext(NearMeContext);
if (!value) throw new Error("useNearMe ต้องถูกใช้ภายใน <NearMeProvider>");
return value;
}
+72
View File
@@ -0,0 +1,72 @@
import { createHmac } from "node:crypto";
import { createError, deleteCookie, getCookie, setCookie, type H3Event } from "h3";
export const ADMIN_COOKIE = "afx_admin";
const SESSION_TTL_SECONDS = 60 * 60 * 8;
const DEFAULT_USERNAME = "it is me";
const DEFAULT_PASSWORD = "it is me&it is me";
function secret(): string {
return process.env.ADMIN_SESSION_SECRET ?? "alterflixhub-local-admin-secret";
}
export function adminCredentials() {
return {
username: process.env.ADMIN_USERNAME ?? DEFAULT_USERNAME,
password: process.env.ADMIN_PASSWORD ?? DEFAULT_PASSWORD,
};
}
export function isValidCredentials(username: string, password: string): boolean {
const expected = adminCredentials();
const given = createHmac("sha256", secret())
.update(`${username}\u0000${password}`)
.digest("hex");
const wanted = createHmac("sha256", secret())
.update(`${expected.username}\u0000${expected.password}`)
.digest("hex");
return given === wanted;
}
function sign(payload: string): string {
return createHmac("sha256", secret()).update(payload).digest("hex");
}
function createToken(): string {
const expiresAt = String(Date.now() + SESSION_TTL_SECONDS * 1000);
return `${expiresAt}.${sign(expiresAt)}`;
}
function isTokenValid(token: string | undefined): boolean {
if (!token) return false;
const [expiresAt, signature] = token.split(".");
if (!expiresAt || !signature) return false;
if (Number(expiresAt) < Date.now()) return false;
return sign(expiresAt) === signature;
}
export function createAdminSession(event: H3Event): void {
setCookie(event, ADMIN_COOKIE, createToken(), {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: SESSION_TTL_SECONDS,
});
}
export function clearAdminSession(event: H3Event): void {
deleteCookie(event, ADMIN_COOKIE, { path: "/" });
}
export function isAdmin(event: H3Event): boolean {
return isTokenValid(getCookie(event, ADMIN_COOKIE));
}
/** ใช้ใน API route ที่ต้องล็อกอินก่อน */
export function requireAdmin(event: H3Event): void {
if (!isAdmin(event)) {
throw createError({ statusCode: 401, statusMessage: "ต้องเข้าสู่ระบบก่อน" });
}
}
+41
View File
@@ -0,0 +1,41 @@
import type { AnalyticsEventType } from "@/lib/analytics-types";
export type TrackInput = {
type: AnalyticsEventType;
query?: string;
category?: string;
result_count?: number;
slug?: string;
source?: string;
position?: number;
locale?: string;
};
const DEDUPE_WINDOW_MS = 1500;
const recent = new Map<string, number>();
/**
* ส่ง event สถิติไปที่ /api/analytics/collect
* - กลืน error ทั้งหมด (สถิติต้องไม่ทำให้หน้าเว็บพัง)
* - กัน event ซ้ำใน 1.5 วินาที (เช่น effect ยิงซ้ำตอน re-render)
*/
export function trackEvent(input: TrackInput): void {
if (typeof window === "undefined") return;
const key = JSON.stringify(input);
const now = Date.now();
const last = recent.get(key);
if (last !== undefined && now - last < DEDUPE_WINDOW_MS) return;
recent.set(key, now);
try {
void fetch("/api/analytics/collect", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ events: [input] }),
keepalive: true,
}).catch(() => undefined);
} catch {
// ไม่ทำอะไร — ปล่อยให้หน้าเว็บทำงานต่อ
}
}
+53
View File
@@ -0,0 +1,53 @@
/**
* สถิติแบบ privacy-first (แนวเดียวกับ Umami): ไม่ใช้คุกกี้ ไม่เก็บ IP/UA ดิบ
* เก็บเป็น event ต่อบรรทัด (JSONL) แล้วสรุปผลฝั่งเซิร์ฟเวอร์
*/
export type AnalyticsEventType = "search" | "cinema_select" | "cinema_view" | "near_me";
export type AnalyticsEvent = {
type: AnalyticsEventType;
/** เวลาที่เกิดเหตุ (ISO) — เซิร์ฟเวอร์เป็นผู้กำหนด */
at: string;
/** รหัสผู้เข้าชมแบบไม่ระบุตัวตน (sha256 ของ ip+ua+เกลือรายวัน) */
visitor: string;
locale: string;
/** คำค้น (เฉพาะ type=search) */
query?: string;
category?: string;
result_count?: number;
slug?: string;
/** ที่มาของการคลิก: search | category | near_me | other_cinemas */
source?: string;
position?: number;
};
export type SearchQueryStat = {
query: string;
count: number;
zero_result_count: number;
click_count: number;
};
export type CinemaStat = {
slug: string;
views: number;
selects: number;
};
export type AnalyticsSummary = {
range_days: number;
total_searches: number;
unique_visitors: number;
zero_result_searches: number;
near_me_uses: number;
average_results: number;
click_through_rate: number;
top_queries: SearchQueryStat[];
zero_result_queries: SearchQueryStat[];
top_categories: Array<{ category: string; count: number }>;
top_cinemas: CinemaStat[];
daily_searches: Array<{ date: string; count: number }>;
/** คำค้นล่าสุด เพื่อดูพฤติกรรมสด ๆ ในหลังบ้าน */
recent_searches: Array<{ at: string; query: string; result_count: number }>;
};
+173
View File
@@ -0,0 +1,173 @@
import { appendFile, mkdir, readFile, rename, stat } from "node:fs/promises";
import path from "node:path";
import type {
AnalyticsEvent,
AnalyticsSummary,
CinemaStat,
SearchQueryStat,
} from "@/lib/analytics-types";
const ANALYTICS_DIR = path.join(process.cwd(), "data", "analytics");
const EVENTS_FILE = path.join(ANALYTICS_DIR, "events.jsonl");
/** เก็บสูงสุดเท่านี้แล้วหมุนไฟล์ เพื่อไม่ให้อ่านช้าเมื่อนานวัน */
const MAX_EVENTS = 50_000;
function normalizeQuery(query: string): string {
return query.trim().toLowerCase().replace(/\s+/g, " ");
}
export async function appendEvent(event: AnalyticsEvent): Promise<void> {
await mkdir(ANALYTICS_DIR, { recursive: true });
await appendFile(EVENTS_FILE, `${JSON.stringify(event)}\n`, "utf8");
await rotateIfNeeded();
}
async function rotateIfNeeded(): Promise<void> {
try {
const info = await stat(EVENTS_FILE);
if (info.size < 8 * 1024 * 1024) return;
await rename(EVENTS_FILE, `${EVENTS_FILE}.${Date.now()}.bak`);
} catch {
// ไฟล์ยังไม่เกิด — ไม่ต้องหมุน
}
}
export async function readEvents(): Promise<AnalyticsEvent[]> {
try {
const raw = await readFile(EVENTS_FILE, "utf8");
return raw
.split("\n")
.filter((line) => line.trim() !== "")
.flatMap((line) => {
try {
return [JSON.parse(line) as AnalyticsEvent];
} catch {
return [];
}
})
.slice(-MAX_EVENTS);
} catch {
return [];
}
}
function percentage(part: number, whole: number): number {
if (whole === 0) return 0;
return Math.round((part / whole) * 1000) / 10;
}
/** สรุปสถิติการค้นหา/การเลือกโรงหนังในช่วง N วันล่าสุด */
export function summarize(
events: AnalyticsEvent[],
rangeDays: number,
now = Date.now(),
): AnalyticsSummary {
const since = now - rangeDays * 24 * 60 * 60 * 1000;
const inRange = events.filter((event) => {
const time = Date.parse(event.at);
return Number.isFinite(time) && time >= since;
});
const searches = inRange.filter((event) => event.type === "search");
const selects = inRange.filter((event) => event.type === "cinema_select");
const visitors = new Set(inRange.map((event) => event.visitor));
const queryMap = new Map<string, SearchQueryStat>();
const categoryMap = new Map<string, number>();
const dailyMap = new Map<string, number>();
const cinemaMap = new Map<string, CinemaStat>();
let resultTotal = 0;
let zeroResults = 0;
for (const event of searches) {
const query = normalizeQuery(event.query ?? "");
if (query === "") continue;
const stat = queryMap.get(query) ?? {
query,
count: 0,
zero_result_count: 0,
click_count: 0,
};
stat.count += 1;
if ((event.result_count ?? 0) === 0) stat.zero_result_count += 1;
queryMap.set(query, stat);
resultTotal += event.result_count ?? 0;
if ((event.result_count ?? 0) === 0) zeroResults += 1;
const category = event.category ?? "ทั้งหมด";
categoryMap.set(category, (categoryMap.get(category) ?? 0) + 1);
const date = event.at.slice(0, 10);
dailyMap.set(date, (dailyMap.get(date) ?? 0) + 1);
}
for (const event of selects) {
const slug = event.slug ?? "";
if (slug === "") continue;
const stat = cinemaMap.get(slug) ?? { slug, views: 0, selects: 0 };
stat.selects += 1;
cinemaMap.set(slug, stat);
// นับคลิกให้คำค้นที่ผู้ใช้ค้นล่าสุด (ถ้ามี source=search)
if (event.source === "search" && event.query) {
const query = normalizeQuery(event.query);
const queryStat = queryMap.get(query);
if (queryStat) queryStat.click_count += 1;
}
}
for (const event of inRange) {
if (event.type !== "cinema_view" || !event.slug) continue;
const stat = cinemaMap.get(event.slug) ?? {
slug: event.slug,
views: 0,
selects: 0,
};
stat.views += 1;
cinemaMap.set(event.slug, stat);
}
const allQueries = Array.from(queryMap.values()).sort(
(first, second) => second.count - first.count,
);
return {
range_days: rangeDays,
total_searches: searches.length,
unique_visitors: visitors.size,
zero_result_searches: zeroResults,
near_me_uses: inRange.filter((event) => event.type === "near_me").length,
average_results:
searches.length === 0 ? 0 : Math.round((resultTotal / searches.length) * 10) / 10,
click_through_rate: percentage(selects.length, searches.length),
top_queries: allQueries.slice(0, 20),
zero_result_queries: allQueries
.filter((stat) => stat.zero_result_count > 0)
.sort((first, second) => second.zero_result_count - first.zero_result_count)
.slice(0, 10),
top_categories: Array.from(categoryMap.entries())
.map(([category, count]) => ({ category, count }))
.sort((first, second) => second.count - first.count)
.slice(0, 10),
top_cinemas: Array.from(cinemaMap.values())
.sort(
(first, second) =>
second.selects + second.views - (first.selects + first.views),
)
.slice(0, 10),
daily_searches: Array.from(dailyMap.entries())
.map(([date, count]) => ({ date, count }))
.sort((first, second) => first.date.localeCompare(second.date)),
recent_searches: [...searches]
.sort((first, second) => second.at.localeCompare(first.at))
.slice(0, 15)
.map((event) => ({
at: event.at,
query: normalizeQuery(event.query ?? ""),
result_count: event.result_count ?? 0,
}))
.filter((row) => row.query !== ""),
};
}
+70
View File
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vitest";
import { summarize } from "./analytics.server";
import type { AnalyticsEvent } from "./analytics-types";
const NOW = Date.parse("2026-10-29T10:00:00.000Z");
function event(partial: Partial<AnalyticsEvent>): AnalyticsEvent {
return {
type: "search",
at: "2026-10-29T09:00:00.000Z",
visitor: "v1",
locale: "th",
...partial,
};
}
describe("summarize", () => {
const events: AnalyticsEvent[] = [
event({ query: "House Samyan", result_count: 1 }),
event({ query: "house samyan", result_count: 1 }),
event({ query: "ไม่มีโรงนี้", result_count: 0, visitor: "v2" }),
event({ query: "อาร์ตเฮาส์", category: "อาร์ตเฮาส์", result_count: 2 }),
event({ type: "cinema_select", slug: "house-cinema-samyan", source: "search", query: "house samyan" }),
event({ type: "cinema_view", slug: "house-cinema-samyan" }),
event({ type: "near_me", result_count: 6 }),
// เก่าเกินช่วง 7 วัน — ต้องไม่ถูกนับ
event({ query: "เก่ามาก", at: "2026-10-01T09:00:00.000Z" }),
];
const summary = summarize(events, 7, NOW);
it("นับเฉพาะ event ในช่วงเวลา", () => {
expect(summary.total_searches).toBe(4);
});
it("นับผู้เข้าชมไม่ซ้ำจาก hash", () => {
expect(summary.unique_visitors).toBe(2);
});
it("รวมคำค้นที่ต่างแค่ช่องว่าง/ตัวพิมพ์ และนับครั้งที่ค้นไม่พบ", () => {
const house = summary.top_queries.find((row) => row.query === "house samyan");
expect(house?.count).toBe(2);
expect(summary.top_queries.find((row) => row.query === "ไม่มีโรงนี้")?.zero_result_count).toBe(1);
expect(summary.zero_result_searches).toBe(1);
});
it("นับคลิกต่อคำค้นและการเปิดดูโรงหนัง", () => {
const house = summary.top_queries.find((row) => row.query === "house samyan");
expect(house?.click_count).toBe(1);
const cinema = summary.top_cinemas.find((row) => row.slug === "house-cinema-samyan");
expect(cinema).toEqual({ slug: "house-cinema-samyan", views: 1, selects: 1 });
});
it("สรุปจำนวนครั้งที่ใช้ ใกล้ฉัน และ CTR", () => {
expect(summary.near_me_uses).toBe(1);
expect(summary.click_through_rate).toBe(25);
});
it("ผลลัพธ์เฉลี่ยต่อการค้นหา", () => {
expect(summary.average_results).toBe(1);
});
it("คำค้นล่าสุดเรียงจากใหม่ไปเก่าและตัด event นอกช่วงออก", () => {
expect(summary.recent_searches.length).toBeGreaterThan(0);
const times = summary.recent_searches.map((row) => row.at);
expect([...times].sort((a, b) => b.localeCompare(a))).toEqual(times);
expect(summary.recent_searches.some((row) => row.query === "เก่ามาก")).toBe(false);
});
});
+11
View File
@@ -0,0 +1,11 @@
const rawAppName = "alterflixhub";
const rawAppTitle = "AlterFlixHub";
const APP_NAME_PLACEHOLDER = "{" + "{APP_NAME}}";
const APP_TITLE_PLACEHOLDER = "{" + "{APP_TITLE}}";
export const APP_NAME =
rawAppName === APP_NAME_PLACEHOLDER ? "chat" : rawAppName;
export const APP_TITLE =
rawAppTitle === APP_TITLE_PLACEHOLDER ? "Chat" : rawAppTitle;
+83
View File
@@ -0,0 +1,83 @@
import { describe, expect, it } from "vitest";
import type { Cinema } from "@/lib/cinemas";
import {
cinemaFacilities,
filterCinemas,
listOtherCinemas,
publiclyVisible,
} from "@/lib/cinemas";
/**
* สเปกของกติกาที่เพิ่มเข้ามา: ซ่อนโรง (hidden) + สิ่งอำนวยความสะดวกต่อโรง
*/
function cinema(slug: string, patch: Partial<Cinema> = {}): Cinema {
return {
slug,
name: slug.toUpperCase(),
name_th: slug,
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
...patch,
};
}
describe("cinemaFacilities", () => {
it("คืนเฉพาะหัวข้อที่มี และเรียงตาม FACILITY_KEYS", () => {
const c = cinema("a", { facilities: ["cafe", "seating"] });
expect(cinemaFacilities(c)).toEqual(["seating", "cafe"]);
});
it("ข้อมูลเก่าที่ไม่มีฟิลด์ → อาร์เรย์ว่าง", () => {
expect(cinemaFacilities(cinema("b"))).toEqual([]);
});
it("ตัดคีย์ที่ไม่รู้จักทิ้ง", () => {
const c = cinema("c", { facilities: ["seating", "unknown" as never] });
expect(cinemaFacilities(c)).toEqual(["seating"]);
});
});
describe("publiclyVisible", () => {
it("ตัดโรงที่ hidden ออก", () => {
const list = [cinema("a"), cinema("b", { hidden: true }), cinema("c")];
expect(publiclyVisible(list).map((item) => item.slug)).toEqual(["a", "c"]);
});
});
describe("filterCinemas + hidden", () => {
it("ตัวกรองหมวดไม่คืนโรงที่ถูกซ่อน (เพราะกรองจากลิสต์ที่ผ่าน publiclyVisible)", () => {
const list = [
cinema("show", { tags: ["อาร์ตเฮาส์"] }),
cinema("hide", { tags: ["อาร์ตเฮาส์"], hidden: true }),
];
const result = filterCinemas(publiclyVisible(list), { category: "อาร์ตเฮาส์", query: "" });
expect(result.map((item) => item.slug)).toEqual(["show"]);
});
it("ค้นหาจากชื่อ/ที่ตั้ง ยังทำงาน", () => {
const list = [cinema("x", { location_label: "จังหวัดพะเยา" })];
expect(filterCinemas(list, { category: "ทั้งหมด", query: "พะเยา" })).toHaveLength(1);
});
});
describe("listOtherCinemas", () => {
it("ไม่คืนตัวเอง และไม่คืนโรงที่ซ่อน", () => {
const list = [cinema("a"), cinema("b", { hidden: true }), cinema("c")];
expect(listOtherCinemas(list, "a").map((item) => item.slug)).toEqual(["c"]);
});
it("จำกัดจำนวนตาม limit", () => {
const list = [cinema("a"), cinema("b"), cinema("c"), cinema("d")];
expect(listOtherCinemas(list, "a", 2)).toHaveLength(2);
});
});
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
DEFAULT_CATEGORY,
filterCinemas,
findCinemaBySlug,
listOtherCinemas,
CINEMAS,
} from "./cinemas";
describe("filterCinemas", () => {
it("คืนทุกโรงหนังเมื่อเลือกหมวดทั้งหมดและไม่พิมพ์ค้นหา", () => {
const result = filterCinemas(CINEMAS, { category: DEFAULT_CATEGORY, query: "" });
expect(result.length).toBeGreaterThan(0);
});
it("กรองตามหมวดหมู่จาก tags", () => {
const result = filterCinemas(CINEMAS, { category: "อาร์ตเฮาส์", query: "" });
expect(result.length).toBeGreaterThan(0);
expect(result.every((cinema) => cinema.tags.includes("อาร์ตเฮาส์"))).toBe(
true,
);
});
it("ค้นหาแบบไม่สนตัวพิมพ์และตัดช่องว่างหัวท้าย", () => {
const result = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: " house ",
});
expect(result.map((cinema) => cinema.slug)).toContain(
"house-cinema-samyan",
);
});
it("คืนอาร์เรย์ว่างเมื่อไม่พบคำค้น", () => {
expect(
filterCinemas(CINEMAS, { category: DEFAULT_CATEGORY, query: "ไม่มีโรงนี้แน่นอน" }),
).toEqual([]);
});
});
describe("findCinemaBySlug", () => {
it("คืน undefined เมื่อไม่ได้ส่ง slug", () => {
expect(findCinemaBySlug(CINEMAS, undefined)).toBeUndefined();
});
it("คืนโรงหนังตาม slug", () => {
expect(findCinemaBySlug(CINEMAS, "house-cinema-samyan")?.name).toBe(
"HOUSE CINEMA SAMYAN",
);
});
});
describe("listOtherCinemas", () => {
it("ไม่รวมโรงหนังปัจจุบันและไม่เกิน limit", () => {
const others = listOtherCinemas(CINEMAS, "house-cinema-samyan", 4);
expect(others).toHaveLength(4);
expect(others.map((cinema) => cinema.slug)).not.toContain(
"house-cinema-samyan",
);
});
});
+401
View File
@@ -0,0 +1,401 @@
/**
* ข้อมูลโรงหนังอิสระ — แหล่งข้อมูลเดียวของทั้งหน้าแรกและหน้ารายละเอียด
* ค่าที่ไม่รู้จริงปล่อยเป็นค่าว่าง/null แล้ว UI แสดงข้อความสำรองตามภาษา (lib/i18n)
* ข้อความอังกฤษเป็นฟิลด์เสริม (*_en) ถ้าไม่กรอกจะ fallback เป็นไทย
*/
import type { FacilityKey, Locale, Messages } from "@/lib/i18n/messages";
import { FACILITY_KEYS } from "@/lib/i18n/messages";
import type { Coordinates } from "@/lib/geo";
export type TransportMode = {
/** ใช้เลือกไอคอนและชื่อวิธีเดินทางจากข้อความแปล */
icon_name: "private_car" | "metro" | "bus";
/** รายละเอียดเส้นทาง — ภาษาตามข้อมูล (ยังไม่มีฟิลด์ _en) */
value: string;
value_en?: string;
};
export type ContactChannel = {
label: string;
value: string;
href: string | null;
};
export type Cinema = {
slug: string;
name: string;
/** ชื่อภาษาไทย (ไม่กรอกก็ใช้ name อังกฤษ) */
name_th?: string;
tags: string[];
location_label: string;
location_label_en?: string;
/** พิกัดโรงหนังสำหรับคำนวณระยะทาง — null คือยังไม่ทราบตำแหน่งจริง */
coordinates: Coordinates | null;
description: string;
description_en?: string;
map_url: string | null;
address_lines: string[];
address_lines_en?: string[];
transport: TransportMode[];
contacts: ContactChannel[];
payments: string[];
/** สิ่งอำนวยความสะดวกที่มีจริง — คีย์ตาม FACILITY_KEYS (ไม่กรอก = ไม่ระบุ) */
facilities?: FacilityKey[];
/**
* ข้อความเฉพาะโรงนี้ต่อหัวข้อ (ทับค่าเริ่มต้นจาก messages.ts)
* label = ชื่อหัวข้อ (ไม่แยกภาษา) · sub_th/sub_en = คำอธิบาย
*/
facility_details?: Partial<
Record<FacilityKey, { label?: string; sub_th?: string; sub_en?: string }>
>;
/** ซ่อนจากหน้าเว็บ (ยังเปิดดูได้ด้วย URL ตรง) — ไม่แสดงในรายการ/ค้นหา/โรงอื่นๆ */
hidden?: boolean;
/** หัวข้อการ์ดติดต่อ/จองตั๋ว เฉพาะโรงนี้ (ว่าง = ใช้ค่าเริ่มต้นจาก messages) */
contact_heading?: string;
/** รูปโรงหนัง เรียงตามลำดับที่ใช้ในแกลเลอรี — ว่างได้ถ้ายังไม่มีรูป */
photos: string[];
};
export const CINEMA_CATEGORIES = [
"ทั้งหมด",
"ยอดนิยม",
"อาร์ตเฮาส์",
"สารคดี",
"หนังสั้น",
"หนังคลาสสิก",
"หนังนานาชาติ",
"หนังนอกกระแส",
"หนังในกระแส",
"หนังฝรั่งเศส",
"กลุ่มคนฉายหนัง",
"หนังไทย",
] as const;
export type CinemaCategory = (typeof CINEMA_CATEGORIES)[number];
export const DEFAULT_CATEGORY: CinemaCategory = "ทั้งหมด";
/** ลำดับ gradient ของการ์ด ใช้ร่วมกันทุกหน้าเพื่อให้สีคงที่ */
export 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]",
] as const;
export const CINEMAS: Cinema[] = [
{
slug: "house-cinema-samyan",
name: "HOUSE CINEMA SAMYAN",
name_th: "HOUSE สามย่าน",
tags: ["หนังนอกกระแส", "อาร์ตเฮาส์"],
location_label: "ชั้น 5 สามย่านมิตรทาวน์ กรุงเทพฯ",
location_label_en: "5th floor, Samyan Mitrtown, Bangkok",
coordinates: { latitude: 13.7343452, longitude: 100.5282654 },
description:
"โรงภาพยนตร์สำหรับคนที่อยากค้นพบหนังหลากหลาย เน้นภาพยนตร์นอกกระแสและเรื่องที่ไม่ได้เข้าฉายในวงกว้าง พร้อมเรื่องราวและมุมมองที่แตกต่างสำหรับคนรักหนัง",
description_en:
"A cinema for people who want to discover a wide range of films — focused on independent titles and stories that never reach a wide release, with perspectives made for film lovers.",
map_url: "https://maps.google.com/?q=House+Samyan",
address_lines: [
"ชั้น 5 ศูนย์การค้าสามย่านมิตรทาวน์",
"944/1 ถนนพระราม 4 แขวงวังใหม่ เขตปทุมวัน กรุงเทพฯ 10330",
],
address_lines_en: [
"5th floor, Samyan Mitrtown",
"944/1 Rama IV Road, Wang Mai, Pathum Wan, Bangkok 10330",
],
transport: [
{
icon_name: "private_car",
value: "ที่จอดรถภายในศูนย์การค้าสามย่านมิตรทาวน์",
value_en: "Parking inside Samyan Mitrtown",
},
{
icon_name: "metro",
value: "MRT สถานีสามย่าน",
value_en: "MRT Sam Yan station",
},
{
icon_name: "bus",
value: "29, 34, 36, 40, 47, 50",
value_en: "29, 34, 36, 40, 47, 50",
},
],
contacts: [
{
label: "Website",
value: "www.housesamyan.com",
href: "https://www.housesamyan.com",
},
{
label: "Facebook",
value: "House Samyan",
href: "https://www.facebook.com/housesamyan",
},
{ label: "Call", value: "098-869-0997", href: "tel:0988690997" },
],
payments: ["เงินสด", "บัตรเครดิต", "สแกนจ่าย"],
// ใส่ path รูปจริง เช่น "/images/cinemas/house-samyan/1.jpg" — ป้าย "+N" คำนวณจากความยาวอาร์เรย์นี้
photos: [],
},
{
slug: "thana-cineplex",
name: "THANA CINEPLEX",
tags: ["หนังในกระแส", "ยอดนิยม"],
location_label: "เดอะมอลล์งามวงศ์วาน นนทบุรี",
location_label_en: "The Mall Ngamwongwan, Nonthaburi",
coordinates: { latitude: 13.8564363, longitude: 100.5419053 },
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "century-the-movie-plaza",
name: "CENTURY",
name_th: "เซ็นจูรี่มูฟวี่พลาซ่า",
tags: ["หนังในกระแส"],
location_label: "เซ็นจูรี่ เดอะมูฟวี่ พลาซ่า อนุสาวรีย์ชัยฯ กรุงเทพฯ",
location_label_en: "Century The Movie Plaza, Victory Monument, Bangkok",
coordinates: { latitude: 13.7616674, longitude: 100.5371572 },
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "ck-plaza",
name: "CK PLAZA",
tags: ["หนังในกระแส"],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "major-hollywood",
name: "MAJOR HOLLYWOOD",
tags: ["หนังในกระแส", "ยอดนิยม"],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "coliseum-paradise",
name: "COLISEUM PARADISE",
tags: ["หนังคลาสสิก", "อาร์ตเฮาส์"],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
// รายการที่ผู้ใช้ให้มา — ใส่เฉพาะชื่อ TH/EN ฟิลด์อื่นรอเติม
{
slug: "alliance-francaise-de-bangkok",
name: "Alliance Française de Bangkok",
name_th: "สมาคมฝรั่งเศสกรุงเทพ",
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "cinema-oasis",
name: "Cinema Oasis",
name_th: "มูลนิธิซิเนม่าโอเอซิส",
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "the-friese-greene-club",
name: "The Friese-Greene Club",
name_th: "เดอะ ฟรีส-กรีน คลับ",
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "century-the-movie-plaza-sukhumvit",
name: "Century - The Movie Plaza Sukhumvit",
name_th: "เซ็นจูรี่มูวี่พลาซ่า สุขุมวิท",
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
{
slug: "thai-film-archive",
name: "Thai Film Archive",
name_th: "หอภาพยนตร์",
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
},
];
/** ฟิลด์ที่มี *_en จะใช้เมื่อภาษาเป็นอังกฤษ และ fallback เป็นไทยเมื่อยังไม่แปล */
function pick(primary: string, english: string | undefined, locale: Locale) {
return locale === "en" && english ? english : primary;
}
function pickList(
primary: string[],
english: string[] | undefined,
locale: Locale,
): string[] {
return locale === "en" && english && english.length > 0 ? english : primary;
}
export function cinemaLocationLabel(cinema: Cinema, locale: Locale): string {
return pick(cinema.location_label, cinema.location_label_en, locale);
}
/** ชื่อที่แสดงตามภาษา — ไทยใช้ name_th ถ้ามี ไม่งั้นใช้ชื่ออังกฤษ */
export function cinemaName(cinema: Cinema, locale: Locale): string {
if (locale === "th" && cinema.name_th) return cinema.name_th;
return cinema.name;
}
export function cinemaDescription(cinema: Cinema, locale: Locale): string {
return pick(cinema.description, cinema.description_en, locale);
}
export function cinemaAddressLines(cinema: Cinema, locale: Locale): string[] {
return pickList(cinema.address_lines, cinema.address_lines_en, locale);
}
/**
* สิ่งอำนวยความสะดวกของโรงนี้ เรียงตาม FACILITY_KEYS
* ข้อมูลเก่าที่ไม่มีฟิลด์นี้จะได้อาร์เรย์ว่าง (UI แสดง "ไม่มีข้อมูล")
*/
export function cinemaFacilities(cinema: Cinema): FacilityKey[] {
const selected = new Set(cinema.facilities ?? []);
return FACILITY_KEYS.filter((key) => selected.has(key));
}
/** หมวดที่เลือกได้ในหลังบ้าน — ตัด "ทั้งหมด" ออกเพราะใช้เป็นตัวกรอง "ไม่กรอง" */
export const ASSIGNABLE_CATEGORIES: CinemaCategory[] =
CINEMA_CATEGORIES.filter((category) => category !== DEFAULT_CATEGORY);
export function transportValue(route: TransportMode, locale: Locale): string {
return pick(route.value, route.value_en, locale);
}
/** ประเภทภาพยนตร์ที่แสดงบนการ์ด สร้างจาก tags เพื่อไม่ต้องกรอกซ้ำ */
export function cinemaCategoryLabel(
cinema: Cinema,
messages: Messages,
): string {
return cinema.tags.map((tag) => messages.tags[tag] ?? tag).join(" · ");
}
export function hasCategory(cinema: Cinema, category: CinemaCategory): boolean {
return category === DEFAULT_CATEGORY || cinema.tags.includes(category);
}
export function matchesQuery(cinema: Cinema, query: string): boolean {
const keyword = query.trim().toLowerCase();
if (keyword === "") return true;
return (
cinema.name.toLowerCase().includes(keyword) ||
cinema.location_label.toLowerCase().includes(keyword) ||
(cinema.location_label_en ?? "").toLowerCase().includes(keyword)
);
}
export function filterCinemas(
cinemas: Cinema[],
{
category,
query,
}: {
category: CinemaCategory;
query: string;
},
): Cinema[] {
return cinemas.filter(
(cinema) => hasCategory(cinema, category) && matchesQuery(cinema, query),
);
}
export function findCinemaBySlug(
cinemas: Cinema[],
slug: string | undefined,
): Cinema | undefined {
if (!slug) return undefined;
return cinemas.find((cinema) => cinema.slug === slug);
}
export function listOtherCinemas(
cinemas: Cinema[],
slug: string,
limit = 4,
): Cinema[] {
return cinemas
.filter((cinema) => cinema.slug !== slug && !cinema.hidden)
.slice(0, limit);
}
/** โรงหนังที่แสดงบนหน้าเว็บ (ตัดตัวที่ถูกซ่อนในหลังบ้านออก) */
export function publiclyVisible(cinemas: Cinema[]): Cinema[] {
return cinemas.filter((cinema) => !cinema.hidden);
}
+24
View File
@@ -0,0 +1,24 @@
import { createContext, useContext, type ReactNode } from "react";
import type { ContentStore } from "@/lib/content-types";
const ContentContext = createContext<ContentStore | null>(null);
/** เนื้อหาที่แก้ได้ (โรงหนัง/คำศัพท์/footer) จาก loader ของ root */
export function ContentProvider({
content,
children,
}: {
content: ContentStore;
children: ReactNode;
}) {
return (
<ContentContext.Provider value={content}>{children}</ContentContext.Provider>
);
}
export function useContent(): ContentStore {
const value = useContext(ContentContext);
if (!value) throw new Error("useContent ต้องถูกใช้ภายใน <ContentProvider>");
return value;
}
+115
View File
@@ -0,0 +1,115 @@
import { CINEMAS } from "@/lib/cinemas";
import type { Locale } from "@/lib/i18n/messages";
import { MESSAGES } from "@/lib/i18n/messages";
import type {
AboutContent,
ContentStore,
FooterItem,
LocaleEntry,
TermEntry,
} from "@/lib/content-types";
import type { Messages } from "@/lib/i18n/messages";
export const DEFAULT_LOCALES: LocaleEntry[] = [
{ code: "th", label: "ไทย" },
{ code: "en", label: "English" },
];
function flatten(
value: unknown,
prefix: string,
out: Record<string, string>,
): void {
if (typeof value === "string") {
out[prefix] = value;
return;
}
if (value && typeof value === "object") {
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
flatten(child, prefix ? `${prefix}.${key}` : key, out);
}
}
}
/** รวมข้อความทุกภาษาเป็นรายการคำศัพท์ (ใช้เป็นค่าเริ่มต้นของหน้า admin) */
export function seedTerms(): TermEntry[] {
const perLocale: Record<string, Record<string, string>> = {};
for (const locale of Object.keys(MESSAGES) as Locale[]) {
const flat: Record<string, string> = {};
flatten(MESSAGES[locale], "", flat);
perLocale[locale] = flat;
}
const keys = Object.keys(perLocale.th ?? perLocale.en ?? {});
return keys.map((key) => ({
key,
values: Object.fromEntries(
Object.entries(perLocale).map(([locale, flat]) => [locale, flat[key] ?? ""]),
),
}));
}
export const DEFAULT_FOOTER: FooterItem[] = [
{
id: "facebook",
icon_name: "IconBrandFacebook",
label: "Facebook",
href: "https://www.facebook.com/",
},
{
id: "instagram",
icon_name: "IconBrandInstagram",
label: "Instagram",
href: "https://www.instagram.com/",
},
{
id: "linkedin",
icon_name: "IconBrandLinkedin",
label: "LinkedIn",
href: "https://www.linkedin.com/",
},
{
id: "youtube",
icon_name: "IconBrandYoutube",
label: "YouTube",
href: "https://www.youtube.com/",
},
{
id: "telegram",
icon_name: "IconBrandTelegram",
label: "Telegram",
href: "https://t.me/",
},
];
/** เนื้อหาหน้า "เกี่ยวกับเรา" เริ่มต้น — ดึงจากข้อความ i18n เพื่อไม่ต้องดูแลสองที่ */
export function seedAbout(): Record<Locale, AboutContent> {
return {
th: toAboutContent(MESSAGES.th.about),
en: toAboutContent(MESSAGES.en.about),
};
}
function toAboutContent(source: Messages["about"]): AboutContent {
return {
title: source.title,
lead: source.lead,
sections: source.sections.map((section) => ({
heading: section.heading,
body: section.body,
})),
contactHeading: source.contactHeading,
contactNote: source.contactNote,
};
}
export function seedContent(): ContentStore {
return {
cinemas: CINEMAS,
site: {
locales: DEFAULT_LOCALES,
terms: seedTerms(),
footer: DEFAULT_FOOTER,
},
about: seedAbout(),
};
}
+54
View File
@@ -0,0 +1,54 @@
/**
* โครงข้อมูลที่แก้ได้จากหน้า admin — เก็บเป็น JSON ใต้ data/content/
* หน้าเว็บอ่านค่าชุดนี้ผ่าน loader ของ root (ฝั่ง server เท่านั้น)
*/
import type { Cinema } from "@/lib/cinemas";
import type { Locale } from "@/lib/i18n/messages";
export type AboutSection = {
heading: string;
body: string;
};
/** เนื้อหาหน้า "เกี่ยวกับเรา" หนึ่งภาษา */
export type AboutContent = {
title: string;
lead: string;
sections: AboutSection[];
contactHeading: string;
contactNote: string;
};
export type FooterItem = {
id: string;
/** ชื่อไอคอน Tabler เช่น IconBrandFacebook */
icon_name: string;
label: string;
href: string;
};
export type TermEntry = {
/** dot path เข้าโครงข้อความ เช่น "hero.subtitle" หรือ "categories.อาร์ตเฮาส์" */
key: string;
/** ค่าตามรหัสภาษา เช่น { th: "...", en: "..." } */
values: Record<string, string>;
};
export type LocaleEntry = {
code: string;
label: string;
};
export type SiteContent = {
locales: LocaleEntry[];
terms: TermEntry[];
footer: FooterItem[];
};
export type ContentStore = {
cinemas: Cinema[];
site: SiteContent;
/** เนื้อหาหน้า "เกี่ยวกับเรา" แยกตามภาษา — แก้ได้จากหลังบ้าน */
about: Record<Locale, AboutContent>;
};
+264
View File
@@ -0,0 +1,264 @@
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { seedAbout, seedContent } from "@/lib/content-seed";
import type {
AboutContent,
ContentStore,
FooterItem,
LocaleEntry,
SiteContent,
TermEntry,
} from "@/lib/content-types";
import type { Locale } from "@/lib/i18n/messages";
import { FACILITY_KEYS } from "@/lib/i18n/messages";
import type { Cinema } from "@/lib/cinemas";
const CONTENT_DIR = path.join(process.cwd(), "data", "content");
const CONTENT_FILE = path.join(CONTENT_DIR, "content.json");
let cache: { store: ContentStore; mtimeMs: number } | null = null;
function asString(value: unknown, fallback = ""): string {
return typeof value === "string" ? value : fallback;
}
function asStringList(value: unknown): string[] {
return Array.isArray(value)
? value.filter((item): item is string => typeof item === "string")
: [];
}
function asCoordinates(value: unknown): Cinema["coordinates"] {
if (!value || typeof value !== "object") return null;
const raw = value as { latitude?: unknown; longitude?: unknown };
const latitude = Number(raw.latitude);
const longitude = Number(raw.longitude);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
return { latitude, longitude };
}
/** ตรวจและแปลงสิ่งอำนวยความสะดวก — เก็บเฉพาะคีย์ที่รู้จัก เรียงตาม FACILITY_KEYS */
function sanitizeFacilities(value: unknown): Cinema["facilities"] {
if (!Array.isArray(value)) return [];
const picked = new Set(
value.filter((item): item is string => typeof item === "string"),
);
return FACILITY_KEYS.filter((key) => picked.has(key));
}
/** ตรวจข้อความเฉพาะโรงของแต่ละหัวข้อ — เก็บเฉพาะคีย์/ฟิลด์ที่รู้จัก */
function sanitizeFacilityDetails(
value: unknown,
): Cinema["facility_details"] {
if (!value || typeof value !== "object") return {};
const raw = value as Record<string, unknown>;
const result: NonNullable<Cinema["facility_details"]> = {};
for (const key of FACILITY_KEYS) {
const entry = raw[key];
if (!entry || typeof entry !== "object") continue;
const item = entry as Record<string, unknown>;
const label = asString(item.label).trim();
const subTh = asString(item.sub_th);
const subEn = asString(item.sub_en);
if (label || subTh || subEn) {
result[key] = {
...(label ? { label } : {}),
...(subTh ? { sub_th: subTh } : {}),
...(subEn ? { sub_en: subEn } : {}),
};
}
}
return result;
}
/** ตรวจและแปลงโรงหนังจาก JSON ที่ผู้ใช้แก้/วาง — ฟิลด์ที่ไม่รู้จักถูกทิ้ง */
export function sanitizeCinemas(input: unknown): Cinema[] {
if (!Array.isArray(input)) throw new Error("cinemas ต้องเป็น array");
return input.map((item, index) => {
if (!item || typeof item !== "object") {
throw new Error(`โรงหนังลำดับที่ ${index + 1} ไม่ใช่วัตถุ`);
}
const raw = item as Record<string, unknown>;
const slug = asString(raw.slug).trim();
const name = asString(raw.name).trim();
if (!slug) throw new Error(`โรงหนังลำดับที่ ${index + 1} ไม่มี slug`);
if (!name) throw new Error(`โรงหนัง ${slug} ไม่มีชื่อ`);
return {
slug,
name,
name_th: asString(raw.name_th),
tags: asStringList(raw.tags),
location_label: asString(raw.location_label),
location_label_en: asString(raw.location_label_en),
coordinates: asCoordinates(raw.coordinates),
description: asString(raw.description),
description_en: asString(raw.description_en),
map_url: typeof raw.map_url === "string" ? raw.map_url : null,
address_lines: asStringList(raw.address_lines),
address_lines_en: asStringList(raw.address_lines_en),
transport: Array.isArray(raw.transport)
? raw.transport.map((route) => {
const entry = (route ?? {}) as Record<string, unknown>;
const icon = asString(entry.icon_name, "bus");
return {
icon_name: (["private_car", "metro", "bus"].includes(icon)
? icon
: "bus") as Cinema["transport"][number]["icon_name"],
value: asString(entry.value),
value_en: asString(entry.value_en),
};
})
: [],
contacts: Array.isArray(raw.contacts)
? raw.contacts.map((contact) => {
const entry = (contact ?? {}) as Record<string, unknown>;
return {
label: asString(entry.label),
value: asString(entry.value),
href: typeof entry.href === "string" ? entry.href : null,
};
})
: [],
payments: asStringList(raw.payments),
facilities: sanitizeFacilities(raw.facilities),
facility_details: sanitizeFacilityDetails(raw.facility_details),
hidden: raw.hidden === true,
contact_heading: asString(raw.contact_heading),
photos: asStringList(raw.photos),
};
});
}
export function sanitizeSite(input: unknown): SiteContent {
const seed = seedContent().site;
if (!input || typeof input !== "object") return seed;
const raw = input as Record<string, unknown>;
const locales: LocaleEntry[] = Array.isArray(raw.locales)
? raw.locales
.map((locale) => {
const entry = (locale ?? {}) as Record<string, unknown>;
const code = asString(entry.code).trim();
return code ? { code, label: asString(entry.label, code) } : null;
})
.filter((locale): locale is LocaleEntry => locale !== null)
: seed.locales;
const terms: TermEntry[] = Array.isArray(raw.terms)
? raw.terms
.map((term) => {
const entry = (term ?? {}) as Record<string, unknown>;
const key = asString(entry.key).trim();
if (!key) return null;
const values: Record<string, string> = {};
const rawValues = (entry.values ?? {}) as Record<string, unknown>;
for (const [locale, value] of Object.entries(rawValues)) {
values[locale] = asString(value);
}
return { key, values };
})
.filter((term): term is TermEntry => term !== null)
: seed.terms;
const footer: FooterItem[] = Array.isArray(raw.footer)
? raw.footer
.map((item, index) => {
const entry = (item ?? {}) as Record<string, unknown>;
const label = asString(entry.label).trim();
if (!label) return null;
return {
id: asString(entry.id, `footer-${index + 1}`),
icon_name: asString(entry.icon_name, "IconLink"),
label,
href: asString(entry.href),
};
})
.filter((item): item is FooterItem => item !== null)
: seed.footer;
return {
locales: locales.length > 0 ? locales : seed.locales,
terms: terms.length > 0 ? terms : seed.terms,
footer,
};
}
export function sanitizeAbout(input: unknown): Record<Locale, AboutContent> {
const seed = seedAbout();
if (!input || typeof input !== "object") return seed;
const raw = input as Record<string, unknown>;
function one(value: unknown, fallback: AboutContent): AboutContent {
if (!value || typeof value !== "object") return fallback;
const entry = value as Record<string, unknown>;
const sections = Array.isArray(entry.sections)
? entry.sections
.map((section) => {
const item = (section ?? {}) as Record<string, unknown>;
const heading = asString(item.heading).trim();
const body = asString(item.body).trim();
return heading || body ? { heading, body } : null;
})
.filter((section): section is { heading: string; body: string } => section !== null)
: fallback.sections;
return {
title: asString(entry.title, "").trim() || fallback.title,
lead: asString(entry.lead).trim() || fallback.lead,
sections: sections.length > 0 ? sections : fallback.sections,
contactHeading:
asString(entry.contactHeading).trim() || fallback.contactHeading,
contactNote: asString(entry.contactNote).trim() || fallback.contactNote,
};
}
return {
th: one(raw.th, seed.th),
en: one(raw.en, seed.en),
};
}
/** อ่านเนื้อหาทั้งหมด — สร้างไฟล์เริ่มต้นให้อัตโนมัติเมื่อยังไม่มี */
export async function readContent(): Promise<ContentStore> {
let raw: string;
try {
raw = await readFile(CONTENT_FILE, "utf8");
} catch (error) {
// ไม่มีไฟล์ = ครั้งแรกของโปรเจกต์ → สร้างจาก seed
if ((error as NodeJS.ErrnoException)?.code === "ENOENT") {
const store = seedContent();
await writeContent(store);
return store;
}
throw error;
}
const mtimeMs = raw.length;
if (cache && cache.mtimeMs === mtimeMs) return cache.store;
// ไฟล์เสีย/รูปแบบไม่ถูกต้อง → โยน error ออกไป ห้ามเขียนทับข้อมูลเดิมด้วย seed
const parsed = JSON.parse(raw) as unknown;
const store = sanitizeStore(parsed);
cache = { store, mtimeMs };
return store;
}
function sanitizeStore(input: unknown): ContentStore {
const raw = (input ?? {}) as Record<string, unknown>;
return {
cinemas: sanitizeCinemas(raw.cinemas ?? []),
site: sanitizeSite(raw.site ?? {}),
about: sanitizeAbout(raw.about ?? {}),
};
}
/** เขียนแบบ atomic (tmp → rename) เพื่อไม่ให้อ่านไฟล์ครึ่ง ๆ กลาง ๆ */
export async function writeContent(store: ContentStore): Promise<void> {
await mkdir(CONTENT_DIR, { recursive: true });
const temporary = `${CONTENT_FILE}.tmp`;
await writeFile(temporary, `${JSON.stringify(store, null, 2)}\n`, "utf8");
await rename(temporary, CONTENT_FILE);
cache = null;
}
+79
View File
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import { dailyOrder, dayKey, keepsSamePositions } from "@/lib/daily-order";
/**
* เงื่อนไขที่ผู้ใช้กำหนด: โรงหนังทุกโรงต้องไม่ได้ตำแหน่งการ์ดเดิมติดกัน 2 วัน
*/
function slugs(count: number): string[] {
return Array.from({ length: count }, (_, index) => `cinema-${index + 1}`);
}
function nextDay(key: string, plus = 1): string {
const date = new Date(`${key}T00:00:00Z`);
date.setUTCDate(date.getUTCDate() + plus);
return dayKey(date);
}
describe("dailyOrder", () => {
it("วันเดียวกันให้ลำดับเดิมเสมอ (SSR กับ client ตรงกัน)", () => {
const list = slugs(27);
const a = dailyOrder(list, (slug) => slug, "2026-11-01");
const b = dailyOrder(list, (slug) => slug, "2026-11-01");
expect(a).toEqual(b);
});
it("มีครบทุกรายการ ไม่ซ้ำ ไม่หาย", () => {
const list = slugs(27);
const order = dailyOrder(list, (slug) => slug, "2026-11-01");
expect(order).toHaveLength(27);
expect(new Set(order)).toEqual(new Set(list));
});
it("วันติดกัน: ไม่มีรายการใดอยู่ตำแหน่งเดิม (n = 2..40, 10 วัน)", () => {
for (let count = 2; count <= 40; count += 1) {
const list = slugs(count);
let previous = dailyOrder(list, (slug) => slug, "2026-11-01");
for (let day = 1; day <= 10; day += 1) {
const key = nextDay("2026-11-01", day);
const current = dailyOrder(list, (slug) => slug, key);
const stuck = keepsSamePositions(previous, current, (slug) => slug);
expect({ count, key, stuck }).toEqual({ count, key, stuck: [] });
previous = current;
}
}
});
it("ลำดับเปลี่ยนจริงข้ามวัน (ไม่ใช่อาร์เรย์เดิม)", () => {
const list = slugs(10);
const day1 = dailyOrder(list, (slug) => slug, "2026-11-01");
const day2 = dailyOrder(list, (slug) => slug, "2026-11-02");
expect(day1).not.toEqual(day2);
});
it("ไม่ตรงกับลำดับที่กรอกเข้ามา (มีการสลับจริง ไม่ใช่เรียงเดิม)", () => {
const list = slugs(12);
const order = dailyOrder(list, (slug) => slug, "2026-11-01");
expect(order).not.toEqual(list);
});
it("รายการเดียว/ว่าง ไม่พัง", () => {
expect(dailyOrder(["only"], (slug) => slug, "2026-11-01")).toEqual(["only"]);
expect(dailyOrder([], (slug) => slug, "2026-11-01")).toEqual([]);
});
it("แอดมินสลับลำดับฐาน → ผลลัพธ์เปลี่ยนตาม (seed มาจากลำดับที่กรอก)", () => {
const a = dailyOrder(slugs(8), (slug) => slug, "2026-11-01");
const reversed = [...slugs(8)].reverse();
const b = dailyOrder(reversed, (slug) => slug, "2026-11-01");
expect(a).not.toEqual(b);
});
});
describe("dayKey", () => {
it("คืนรูปแบบ YYYY-MM-DD แบบ UTC", () => {
expect(dayKey(new Date("2026-11-01T23:30:00Z"))).toBe("2026-11-01");
expect(dayKey(new Date("2026-11-02T00:30:00Z"))).toBe("2026-11-02");
});
});
+99
View File
@@ -0,0 +1,99 @@
/**
* ลำดับการ์ดโรงหนังหน้าแรกแบบ "สลับทุกวัน"
*
* เงื่อนไขที่ต้องรับประกัน: โรงหนึ่งจะไม่ได้อยู่ตำแหน่งการ์ดเดิมสองวันติดกัน
* วิธี: สร้าง permutation ฐานจากรายการ (คงที่ทุกวัน — เปลี่ยนเมื่อแอดมินสลับลำดับ)
* แล้ว "หมุน" (rotate) ด้วย offset รายวันที่ไม่เป็น 0 และไม่ซ้ำกับเมื่อวาน
* - หมุนด้วย k ใด ๆ ที่ 1 ≤ k ≤ n-1 → ทุกโรงเลื่อนตำแหน่ง เป็นไปไม่ได้ที่จะอยู่ที่เดิม
* - offset = 1 + (จำนวนวัน % (n-1)) → ค่าอยู่ใน 1..n-1 และวันติดกันไม่มีทางเท่ากัน
* ผลพลอยได้: ทุกคนเห็นลำดับเดียวกันในวันเดียวกัน (ไม่เกิด hydration mismatch)
* และไม่ต้องเก็บ state เพิ่ม — คำนวณจากวันที่ล้วน ๆ
*/
const DAY_MS = 86_400_000;
/** คีย์วันที่แบบ UTC (YYYY-MM-DD) — ใช้ร่วมกันทั้ง SSR และ client */
export function dayKey(date: Date = new Date()): string {
return date.toISOString().slice(0, 10);
}
function daysSinceEpoch(key: string): number {
const parsed = Date.parse(`${key}T00:00:00Z`);
return Number.isFinite(parsed) ? Math.floor(parsed / DAY_MS) : 0;
}
/** hash 32-bit แบบ deterministic (ใช้ seed ของ permutation ฐาน) */
function hashText(text: string): number {
let hash = 2166136261;
for (let index = 0; index < text.length; index += 1) {
hash ^= text.charCodeAt(index);
hash = Math.imul(hash, 16777619);
}
return hash >>> 0;
}
/** PRNG แบบ mulberry32 — ผลซ้ำได้ทุกเครื่องด้วย seed เดียวกัน */
function createRandom(seed: number): () => number {
let state = seed >>> 0;
return () => {
state = (state + 0x6d2b79f5) >>> 0;
let t = state;
t = Math.imul(t ^ (t >>> 15), t | 1);
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
/** Fisher–Yates ด้วย seeded random */
function seededShuffle<T>(items: T[], seed: number): T[] {
const random = createRandom(seed);
const result = [...items];
for (let i = result.length - 1; i > 0; i -= 1) {
const j = Math.floor(random() * (i + 1));
[result[i], result[j]] = [result[j], result[i]];
}
return result;
}
/** หมุนอาร์เรย์ไปทางซ้าย k ตำแหน่ง */
function rotate<T>(items: T[], by: number): T[] {
if (items.length === 0) return [];
const offset = ((by % items.length) + items.length) % items.length;
return [...items.slice(offset), ...items.slice(0, offset)];
}
/**
* ลำดับของวันนั้น ๆ
* @param items รายการ (เรียงตามลำดับที่แอดมินจัดไว้)
* @param idOf ตัวระบุของแต่ละรายการ (ใช้ทำ seed ให้ permutation ฐานนิ่ง)
* @param key วันที่ (YYYY-MM-DD) — ค่าเริ่มต้นคือวันนี้ (UTC)
*/
export function dailyOrder<T>(
items: T[],
idOf: (item: T) => string,
key: string = dayKey(),
): T[] {
const count = items.length;
if (count < 2) return [...items];
const baseSeed = hashText(idOf(items[0]) + "|" + items.map(idOf).join("|") + "|v1");
const base = seededShuffle(items, baseSeed);
const days = daysSinceEpoch(key);
// n = 2: มี permutation ที่ต่างกันได้แค่ 2 แบบ → สลับวันละครั้ง
const offset = count === 2 ? days % 2 : 1 + (((days % (count - 1)) + (count - 1)) % (count - 1));
return rotate(base, offset);
}
/** ตรวจว่าไม่มีรายการใดอยู่ตำแหน่งเดิมเมื่อเทียบสองวัน (ใช้ในเทสต์) */
export function keepsSamePositions<T>(
first: T[],
second: T[],
idOf: (item: T) => string,
): string[] {
const index = new Map(second.map((item, position) => [idOf(item), position]));
return first
.filter((item, position) => index.get(idOf(item)) === position)
.map(idOf);
}
+42
View File
@@ -0,0 +1,42 @@
/**
* ค่าสีที่ดึงจาก Figma — ใช้กับ inline style เท่านั้น
* (className ของ Tailwind ต้องเป็น literal ถึงจะถูก compile จึงไม่ทำ interpolation)
*/
export const COLORS = {
background: "#0D0D0D",
surface: "#1B1B1B",
surfaceRaised: "#1F1F1F",
surfaceChip: "#242424",
surfaceMuted: "#E8E8E8",
border: "#332B2B",
borderSubtle: "#303030",
brand: "#8F0808",
brandBright: "#A92626",
brandText: "#D47272",
brandGlow: "#4C0404",
textPrimary: "#FFFFFF",
textMuted: "#B3B3B3",
textSubtle: "#999999",
glowSoft: "rgba(143,8,8,0.4)",
pillGradient:
"linear-gradient(180deg, rgba(143,8,8,0.3) 0%, rgba(27,27,27,0) 100%)",
flagGradient:
"linear-gradient(#A51931 0 17%, #F4F5F8 17% 34%, #2D2A4A 34% 66%, #F4F5F8 66% 83%, #A51931 83%)",
} as const;
/**
* สเปกโลโก้ — ห้ามเปลี่ยนแปลง (ดู DESIGN.md หัวข้อ "โลโก้")
* ฟอนต์พิกเซล Jersey 15 เท่านั้น สีแดงแบรนด์คงที่ และมีสองขนาดที่อนุญาต
*/
export const LOGO_SPEC = {
wordmark: "AlterFlixHub",
fontFamily: "'Jersey 15', sans-serif",
color: "#8F0808",
/** header ใช้ md (36px) · footer ใช้ sm (24px) */
sizes: {
sm: "text-2xl",
md: "text-4xl",
},
} as const;
export type LogoSize = keyof typeof LOGO_SPEC.sizes;
+38
View File
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { GALLERY_SLOTS, splitGallery } from "./gallery";
const photosOf = (count: number) =>
Array.from({ length: count }, (_, index) => `/images/p${index + 1}.jpg`);
describe("splitGallery", () => {
it("ไม่มีรูป → ไม่มีภาพหลัก ไม่มีป้าย +N", () => {
expect(splitGallery([])).toEqual({ main: null, thumbs: [], remaining: 0 });
});
it("มีรูป 1 ใบ → เป็นภาพหลัก ไม่มีป้าย", () => {
const view = splitGallery(photosOf(1));
expect(view.main).toBe("/images/p1.jpg");
expect(view.thumbs).toEqual([]);
expect(view.remaining).toBe(0);
});
it("มี 3 ใบ (เท่าจำนวนช่อง) → ไม่มีป้าย +N", () => {
const view = splitGallery(photosOf(GALLERY_SLOTS));
expect(view.thumbs).toHaveLength(2);
expect(view.remaining).toBe(0);
});
it("มี 8 ใบ → แสดง 3 ใบและป้าย +5", () => {
const view = splitGallery(photosOf(8));
expect(view.main).toBe("/images/p1.jpg");
expect(view.thumbs).toEqual(["/images/p2.jpg", "/images/p3.jpg"]);
expect(view.remaining).toBe(5);
});
it("ป้าย +N เท่ากับจำนวนรูปจริงลบช่องที่แสดง", () => {
for (const count of [4, 6, 10, 42]) {
expect(splitGallery(photosOf(count)).remaining).toBe(count - GALLERY_SLOTS);
}
});
});
+24
View File
@@ -0,0 +1,24 @@
/** จำนวนช่องภาพที่แกลเลอรีแสดงจริง: 1 ภาพหลัก + 2 ภาพย่อย */
export const GALLERY_SLOTS = 3;
const THUMB_SLOTS = GALLERY_SLOTS - 1;
export type GalleryView = {
main: string | null;
thumbs: string[];
/** จำนวนรูปที่ยังไม่ถูกแสดง ใช้ทำป้าย "+N" — 0 คือไม่ต้องมีป้าย */
remaining: number;
};
/**
* แบ่งรูปทั้งหมดเป็นภาพหลัก + ภาพย่อย และนับรูปที่เหลือ
* ป้าย "+N" จึงมาจากจำนวนรูปจริง ไม่ใช่ค่าคงที่ในโค้ด
*/
export function splitGallery(photos: string[]): GalleryView {
const [main = null, ...rest] = photos;
return {
main,
thumbs: rest.slice(0, THUMB_SLOTS),
remaining: Math.max(rest.length - THUMB_SLOTS, 0),
};
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import {
formatDistance,
haversineKm,
parseOsrmTable,
sortByDistance,
straightLineDistance,
type DistanceResult,
} from "./geo";
const SAMYAN = { latitude: 13.7343452, longitude: 100.5282654 };
const NGAMWONGWAN = { latitude: 13.8564363, longitude: 100.5419053 };
describe("haversineKm", () => {
it("ระยะทางเส้นตรง Samyan → งามวงศ์วาน ประมาณ 13.6 กม.", () => {
const km = haversineKm(SAMYAN, NGAMWONGWAN);
expect(km).toBeGreaterThan(13);
expect(km).toBeLessThan(14.5);
});
it("จุดเดียวกันได้ 0", () => {
expect(haversineKm(SAMYAN, SAMYAN)).toBeCloseTo(0, 5);
});
});
describe("straightLineDistance", () => {
it("ติดป้ายว่าเป็นค่าประมาณ (เส้นตรง × detour factor)", () => {
const result = straightLineDistance(SAMYAN, NGAMWONGWAN);
expect(result.source).toBe("straight");
expect(result.distance_km).toBeGreaterThan(haversineKm(SAMYAN, NGAMWONGWAN));
});
});
describe("parseOsrmTable", () => {
it("ข้ามคอลัมน์แรก (ต้นทาง) และแปลงเมตรเป็นกิโลเมตร", () => {
const parsed = parseOsrmTable([[0, 16989.1, 3576.3]]);
expect(parsed).toHaveLength(2);
expect(parsed[0]).toBeCloseTo(16.9891, 4);
expect(parsed[1]).toBeCloseTo(3.5763, 4);
});
it("ค่า null จาก OSRM กลายเป็น null", () => {
expect(parseOsrmTable([[0, null, 1000]])).toEqual([null, 1]);
});
it("ข้อมูลผิดรูปแบบคืนอาร์เรย์ว่าง", () => {
expect(parseOsrmTable(undefined)).toEqual([]);
expect(parseOsrmTable("nope")).toEqual([]);
});
});
describe("formatDistance", () => {
it("แสดงทศนิยมหนึ่งตำแหน่ง", () => {
expect(formatDistance({ distance_km: 2.44, source: "road" }, "—")).toBe(
"2.4 km.",
);
});
it("ค่าประมาณขึ้นต้นด้วย ≈", () => {
expect(
formatDistance({ distance_km: 16.99, source: "straight" }, "—"),
).toBe("≈ 17.0 km.");
});
it("ไม่มีข้อมูลใช้ข้อความสำรอง", () => {
expect(formatDistance(undefined, "— km.")).toBe("— km.");
});
});
describe("sortByDistance", () => {
const items = [{ slug: "far" }, { slug: "unknown" }, { slug: "near" }];
const distances: Record<string, DistanceResult | undefined> = {
far: { distance_km: 120, source: "road" },
near: { distance_km: 0.8, source: "road" },
};
it("เรียงใกล้สุดก่อน และโรงที่ไม่ทราบระยะทางไปท้ายสุด", () => {
expect(sortByDistance(items, distances).map((item) => item.slug)).toEqual([
"near",
"far",
"unknown",
]);
});
it("ไกล 100 กม. ก็ยังถูกเรียงตามระยะทาง ไม่ถูกตัดออก", () => {
const sorted = sortByDistance(items, distances);
expect(sorted).toHaveLength(items.length);
});
it("ไม่แก้ไขอาร์เรย์ต้นฉบับ", () => {
const original = [...items];
sortByDistance(items, distances);
expect(items).toEqual(original);
});
});
+127
View File
@@ -0,0 +1,127 @@
/**
* คำนวณระยะทางระหว่างตำแหน่งอุปกรณ์กับโรงหนัง
* - ระยะทางตามถนน: OSRM table service (คำขอเดียวได้ทุกโรง)
* - ถ้าเรียกไม่สำเร็จ: ระยะเส้นตรง × factor แล้วติดป้าย "≈" ให้ผู้ใช้รู้ว่าเป็นค่าประมาณ
*/
export type Coordinates = {
latitude: number;
longitude: number;
};
export type DistanceSource = "road" | "straight";
export type DistanceResult = {
distance_km: number;
source: DistanceSource;
};
const OSRM_TABLE_ENDPOINT =
"https://router.project-osrm.org/table/v1/driving";
/** ตัวคูณชดเชยเส้นทางจริงในเมือง (ถนนอ้อมมุมถนน) ใช้เฉพาะตอนคำนวณแบบเส้นตรง */
const DETOUR_FACTOR = 1.35;
const EARTH_RADIUS_KM = 6371;
const OSRM_TIMEOUT_MS = 8000;
function toRadians(degrees: number): number {
return (degrees * Math.PI) / 180;
}
/** ระยะทางเส้นตรงบนผิวโลก */
export function haversineKm(from: Coordinates, to: Coordinates): number {
const deltaLat = toRadians(to.latitude - from.latitude);
const deltaLon = toRadians(to.longitude - from.longitude);
const a =
Math.sin(deltaLat / 2) ** 2 +
Math.cos(toRadians(from.latitude)) *
Math.cos(toRadians(to.latitude)) *
Math.sin(deltaLon / 2) ** 2;
return 2 * EARTH_RADIUS_KM * Math.asin(Math.sqrt(a));
}
export function straightLineDistance(
from: Coordinates,
to: Coordinates,
): DistanceResult {
return {
distance_km: haversineKm(from, to) * DETOUR_FACTOR,
source: "straight",
};
}
/** อ่านเมทริกซ์ระยะทาง (เมตร) จาก OSRM — แถวแรกคือต้นทาง (ตำแหน่งอุปกรณ์) */
export function parseOsrmTable(meters: unknown): (number | null)[] {
if (!Array.isArray(meters) || !Array.isArray(meters[0])) return [];
const firstRow = meters[0] as unknown[];
return firstRow.slice(1).map((value) =>
typeof value === "number" && Number.isFinite(value) ? value / 1000 : null,
);
}
function buildTableUrl(origin: Coordinates, destinations: Coordinates[]): string {
const points = [origin, ...destinations]
.map((point) => `${point.longitude},${point.latitude}`)
.join(";");
return `${OSRM_TABLE_ENDPOINT}/${points}?annotations=distance`;
}
/**
* ระยะทางตามถนนจากตำแหน่งอุปกรณ์ไปยังทุกจุดหมายในคำขอเดียว
* ลำดับผลลัพธ์ตรงกับ `destinations`; จุดที่หาเส้นทางไม่ได้จะคืน null
*/
export async function fetchRoadDistances(
origin: Coordinates,
destinations: Coordinates[],
): Promise<(DistanceResult | null)[]> {
if (destinations.length === 0) return [];
const response = await fetch(buildTableUrl(origin, destinations), {
signal: AbortSignal.timeout(OSRM_TIMEOUT_MS),
});
if (!response.ok) {
throw new Error(`OSRM ตอบกลับ ${response.status}`);
}
const payload = (await response.json()) as {
code?: string;
distances?: unknown;
};
if (payload.code !== "Ok") {
throw new Error(`OSRM code: ${payload.code ?? "unknown"}`);
}
const kilometres = parseOsrmTable(payload.distances);
return destinations.map((_, index) => {
const distance = kilometres[index];
return distance === null || distance === undefined
? null
: { distance_km: distance, source: "road" as const };
});
}
/** ระยะทางที่แสดงบนการ์ด: 1 ตำแหน่งทศนิยม และเติม "≈" เมื่อเป็นค่าประมาณ */
export function formatDistance(
result: DistanceResult | null | undefined,
fallback: string,
): string {
if (!result) return fallback;
const prefix = result.source === "straight" ? "≈ " : "";
return `${prefix}${result.distance_km.toFixed(1)} km.`;
}
/** เรียงจากใกล้สุดไปไกลสุด — โรงที่ยังไม่ทราบระยะทางไปไว้ท้ายเสมอ */
export function sortByDistance<T extends { slug: string }>(
items: T[],
distances: Record<string, DistanceResult | undefined>,
): T[] {
return [...items].sort((first, second) => {
const a = distances[first.slug]?.distance_km;
const b = distances[second.slug]?.distance_km;
if (a === undefined && b === undefined) return 0;
if (a === undefined) return 1;
if (b === undefined) return -1;
return a - b;
});
}
+164
View File
@@ -0,0 +1,164 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import {
DEFAULT_LOCALE,
MESSAGES,
isLocale,
type Locale,
type Messages,
} from "@/lib/i18n/messages";
import { applyTerms } from "@/lib/i18n/merge";
import type { TermEntry } from "@/lib/content-types";
export const LOCALE_COOKIE = "locale";
export const LOCALE_STORAGE_KEY = "alterflixhub.locale";
const LOCALE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;
export type I18nValue = {
locale: Locale;
messages: Messages;
setLocale: (locale: Locale) => void;
};
const I18nContext = createContext<I18nValue | null>(null);
type LocaleSources = {
/** ค่าจาก query string ?lang= (ชนะทุกอย่าง) */
urlLocale?: string | null;
/** ค่าที่เก็บใน localStorage */
stored?: string | null;
/** ค่าจาก cookie */
cookie?: string | null;
};
/**
* เลือกภาษาเริ่มต้นตามลำดับ: ?lang= → localStorage → cookie → ค่าเริ่มต้น (ไทย)
* ตั้งใจไม่ใช้ navigator.language เพราะเว็บนี้เป็นไทย-first
* (ผู้ใช้ที่ต้องการอังกฤษเลือกเองได้ หรือส่งลิงก์ ?lang=en)
*/
export function resolveInitialLocale({
urlLocale,
stored,
cookie,
}: LocaleSources): Locale {
if (isLocale(urlLocale ?? null)) return urlLocale as Locale;
if (isLocale(stored ?? null)) return stored as Locale;
if (isLocale(cookie ?? null)) return cookie as Locale;
return DEFAULT_LOCALE;
}
function readCookieLocale(): string | null {
const match = document.cookie.match(
new RegExp(`(?:^|;\\s*)${LOCALE_COOKIE}=([^;]+)`),
);
return match?.[1] ?? null;
}
function readStoredLocale(): string | null {
try {
return window.localStorage.getItem(LOCALE_STORAGE_KEY);
} catch {
return null;
}
}
export function LocaleProvider({
initialLocale = DEFAULT_LOCALE,
localeFromUrl = null,
terms = [],
children,
}: {
initialLocale?: Locale;
/** ค่า ?lang= ที่ loader อ่านจาก request (ถ้ามี) */
localeFromUrl?: string | null;
terms?: TermEntry[];
children: ReactNode;
}) {
const [locale, setLocaleState] = useState<Locale>(initialLocale);
// loader ของ agent-native ไม่ส่ง cookie เข้ามา จึงอ่านแหล่งอื่นหลัง mount
// (?lang= ถูกส่งมาแล้วทาง initialLocale/localeFromUrl)
useEffect(() => {
const resolved = resolveInitialLocale({
urlLocale: localeFromUrl,
stored: readStoredLocale(),
cookie: readCookieLocale(),
});
setLocaleState((current) => (current === resolved ? current : resolved));
// ตั้งใจให้ทำงานครั้งเดียวตอน mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const setLocale = useCallback((next: Locale) => {
setLocaleState(next);
document.cookie = `${LOCALE_COOKIE}=${next}; path=/; max-age=${LOCALE_MAX_AGE_SECONDS}; samesite=lax`;
try {
window.localStorage.setItem(LOCALE_STORAGE_KEY, next);
} catch {
// โหมดที่บล็อก storage — cookie ยังทำงานแทน
}
}, []);
// เปิดหลายแท็บแล้วสลับภาษาที่แท็บหนึ่ง ให้แท็บอื่นตามด้วย
useEffect(() => {
function handleStorage(event: StorageEvent) {
if (event.key !== LOCALE_STORAGE_KEY || !isLocale(event.newValue)) return;
setLocaleState(event.newValue);
}
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, []);
useEffect(() => {
document.documentElement.lang = locale;
}, [locale]);
const value = useMemo<I18nValue>(
() => ({
locale,
messages: applyTerms(MESSAGES[locale], terms, locale),
setLocale,
}),
[locale, setLocale, terms],
);
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}
export function useI18n(): I18nValue {
const value = useContext(I18nContext);
if (!value) throw new Error("useI18n ต้องถูกใช้ภายใน <LocaleProvider>");
return value;
}
/** อ่านภาษาจาก cookie header — ใช้ได้ทั้งใน browser และ server */
export function readLocaleFromCookieHeader(cookieHeader: string | null): Locale {
if (!cookieHeader) return DEFAULT_LOCALE;
const match = cookieHeader.match(
new RegExp(`(?:^|;\\s*)${LOCALE_COOKIE}=([^;]+)`),
);
const value = match?.[1];
return isLocale(value) ? value : DEFAULT_LOCALE;
}
/** ?lang=th|en จาก URL ของ request (ใช้ใน loader ของ root) */
export function readLocaleFromRequestUrl(request: Request): string | null {
try {
const value = new URL(request.url).searchParams.get("lang");
return isLocale(value) ? value : null;
} catch {
return null;
}
}
export function resolveLocaleFromRequest(request: Request): Locale {
return readLocaleFromCookieHeader(request.headers.get("cookie"));
}
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { resolveInitialLocale } from "./index";
describe("resolveInitialLocale", () => {
it("?lang= ชนะทุกแหล่ง", () => {
expect(resolveInitialLocale({ urlLocale: "en", stored: "th", cookie: "th" })).toBe("en");
expect(resolveInitialLocale({ urlLocale: "th", stored: "en", cookie: "en" })).toBe("th");
});
it("ใช้ค่าที่เคยเลือก (localStorage) ก่อน cookie", () => {
expect(resolveInitialLocale({ stored: "en", cookie: "th" })).toBe("en");
});
it("ถ้าไม่มีใน localStorage ใช้ cookie", () => {
expect(resolveInitialLocale({ cookie: "en" })).toBe("en");
});
it("ไม่เคยเลือกเลย → ไทย (ไทย-first ไม่อิงภาษาของเบราว์เซอร์)", () => {
expect(resolveInitialLocale({})).toBe("th");
});
it("ค่าที่ไม่รู้จักถูกมองข้ามแล้วตกไปค่าเริ่มต้น", () => {
expect(resolveInitialLocale({ urlLocale: "fr", stored: "xx", cookie: null })).toBe("th");
});
});
+55
View File
@@ -0,0 +1,55 @@
import type { Messages } from "@/lib/i18n/messages";
import type { TermEntry } from "@/lib/content-types";
/** clone แบบคงฟังก์ชันไว้ (Messages มีฟังก์ชันเช่น gallery.more — structuredClone ใช้ไม่ได้) */
function cloneMessages<T>(value: T): T {
if (Array.isArray(value)) {
return value.map((item) => cloneMessages(item)) as unknown as T;
}
if (value && typeof value === "object") {
const result: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
result[key] = cloneMessages(child);
}
return result as T;
}
return value;
}
/** เขียนค่าที่ dot path ที่ระบุ ถ้าปลายทางเป็น string เท่านั้น (ไม่ทับฟังก์ชัน) */
function setPath(
target: Record<string, unknown>,
path: string,
value: string,
): void {
const segments = path.split(".");
let cursor: Record<string, unknown> = target;
for (const segment of segments.slice(0, -1)) {
const next = cursor[segment];
if (!next || typeof next !== "object") return;
cursor = next as Record<string, unknown>;
}
const leaf = segments[segments.length - 1];
if (typeof cursor[leaf] !== "string") return;
cursor[leaf] = value;
}
/**
* รวมคำศัพท์ที่แก้จากหลังบ้านทับข้อความตั้งต้น
* คำศัพท์ที่ key ไม่ตรงหรือปลายทางไม่ใช่ข้อความจะถูกข้าม (ไม่ทำให้หน้าพัง)
*/
export function applyTerms(
base: Messages,
terms: TermEntry[],
locale: string,
): Messages {
const draft = cloneMessages(base) as unknown as Record<string, unknown>;
for (const term of terms) {
const value = term.values[locale];
if (typeof value !== "string" || value === "") continue;
setPath(draft, term.key, value);
}
return draft as unknown as Messages;
}
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { LOCALES, MESSAGES, translate } from "@/lib/i18n/messages";
import { CINEMA_CATEGORIES } from "@/lib/cinemas";
describe("i18n messages", () => {
it("มีข้อความครบทุก locale", () => {
for (const locale of LOCALES) {
const messages = MESSAGES[locale];
expect(messages.hero.titleSuffix.length).toBeGreaterThan(0);
expect(messages.list.title.length).toBeGreaterThan(0);
expect(messages.detail.otherCinemas.length).toBeGreaterThan(0);
}
});
it("แปลป้ายได้ครบทุกหมวดหมู่ที่ใช้กรอง", () => {
for (const locale of LOCALES) {
for (const category of CINEMA_CATEGORIES) {
expect(MESSAGES[locale].categories[category]).toBeTruthy();
}
}
});
it("ภาษาอังกฤษต่างจากไทยในข้อความหลัก", () => {
expect(MESSAGES.en.list.title).not.toBe(MESSAGES.th.list.title);
expect(MESSAGES.en.search.submit).not.toBe(MESSAGES.th.search.submit);
});
it("ค่าที่ไม่รู้จักถูกส่งกลับตามเดิม", () => {
expect(translate(MESSAGES.en.tags, "tag-ใหม่")).toBe("tag-ใหม่");
});
});
+403
View File
@@ -0,0 +1,403 @@
import type { CinemaCategory } from "@/lib/cinemas";
export type Locale = "th" | "en";
export const LOCALES: readonly Locale[] = ["th", "en"] as const;
export const DEFAULT_LOCALE: Locale = "th";
export const LOCALE_OPTIONS: ReadonlyArray<{
locale: Locale;
code: string;
name: string;
}> = [
{ locale: "th", code: "TH", name: "ไทย" },
{ locale: "en", code: "EN", name: "English" },
];
export type FacilityKey =
| "seating"
| "ticket"
| "restaurant"
| "cafe"
| "garden"
| "bookstore"
| "colearning"
| "other";
/** ลำดับคีย์สิ่งอำนวยความสะดวกที่ใช้แสดงผลและให้เลือกในหลังบ้าน */
export const FACILITY_KEYS: FacilityKey[] = [
"seating",
"ticket",
"restaurant",
"cafe",
"garden",
"bookstore",
"colearning",
"other",
];
export type TransportKey = "private_car" | "metro" | "bus";
export type Messages = {
meta: {
homeDescription: string;
cinemaNotFoundTitle: string;
};
hero: {
titlePrefix: string;
titleHighlight: string;
titleSuffix: string;
subtitle: string;
};
search: {
placeholder: string;
nearMe: string;
submit: string;
locating: string;
denied: string;
unsupported: string;
error: string;
sortedByDistance: string;
};
nav: {
home: string;
about: string;
};
about: {
title: string;
lead: string;
sections: Array<{ heading: string; body: string }>;
contactHeading: string;
contactNote: string;
};
list: {
title: string;
showMore: string;
empty: string;
};
card: {
seeDetail: string;
distanceFallback: string;
locationFallback: string;
categoryFallback: string;
};
detail: {
back: string;
openMap: string;
contactTitle: string;
paymentMethods: string;
showtimes: string;
facilities: string;
location: string;
otherCinemas: string;
contactsFallback: string;
paymentsFallback: string;
addressFallback: string;
/** ใช้เมื่อไม่มีทั้งแผนที่และพิกัด */
noData: string;
};
gallery: {
main: string;
second: string;
third: string;
previous: string;
next: string;
more: (remaining: number) => string;
};
notFound: {
title: string;
text: string;
cta: string;
};
/** ป้ายของหมวดหมู่ — คีย์ยังเป็นไทยเพื่อใช้กรองข้อมูล */
categories: Record<CinemaCategory, string>;
/** ป้ายของ tag ในข้อมูลโรงหนัง */
tags: Record<string, string>;
facilities: Record<FacilityKey, { title: string; sub: string }>;
transport: Record<TransportKey, string>;
/** ชื่อช่องทางชำระเงิน (คีย์คือค่าที่เก็บในข้อมูล) */
payments: Record<string, string>;
};
const TH: Messages = {
meta: {
homeDescription: "ค้นหาโรงภาพยนตร์อิสระ ทางเลือกในการดูหนัง",
cinemaNotFoundTitle: "ไม่พบโรงหนัง",
},
hero: {
titlePrefix: "ค้นพบ",
titleHighlight: "โรงหนังใหม่ๆ",
titleSuffix: "ใกล้คุณ",
subtitle:
"ค้นหาโรงภาพยนตร์ท้องถิ่น โรงภาพยนตร์อินดี้และกลุ่มคนฉายหนัง ทางเลือกในการดูหนัง",
},
search: {
placeholder: "ค้นหาชื่อโรงหนังหรือสถานที่ / จังหวัด / ประเภทหนัง",
nearMe: "ใกล้ฉัน",
submit: "ค้นหา",
locating: "กำลังหาตำแหน่ง…",
denied: "ไม่ได้รับอนุญาตให้ใช้ตำแหน่ง",
unsupported: "อุปกรณ์นี้ไม่รองรับการหาตำแหน่ง",
error: "หาตำแหน่งไม่สำเร็จ ลองอีกครั้ง",
sortedByDistance: "เรียงจากใกล้สุดไปไกลสุดแล้ว",
},
nav: {
home: "หน้าแรก",
about: "เกี่ยวกับเรา",
},
about: {
title: "เกี่ยวกับเรา",
lead: "AlterFlixHub รวมโรงหนังอิสระและอาร์ตเฮาส์ในประเทศไทยไว้ที่เดียว เพื่อให้คนรักหนังหาโรงที่ตรงใจและไปถึงได้ง่ายขึ้น",
sections: [
{
heading: "เราทำอะไร",
body: "รวมรายชื่อโรงหนังอิสระพร้อมรายละเอียดที่จำเป็น — ประเภทหนัง สิ่งอำนวยความสะดวก การเดินทาง และช่องทางติดต่อ พร้อมปุ่ม “ใกล้ฉัน” ที่เรียงโรงจากใกล้สุดไปไกลสุดด้วยระยะทางตามถนนจริง",
},
{
heading: "ข้อมูลมาจากไหน",
body: "ทีมงานกรอกและแก้ไขข้อมูลผ่านระบบหลังบ้าน พิกัดอ้างอิงจาก OpenStreetMap และคำนวณระยะทางด้วย OSRM หากข้อมูลใดคลาดเคลื่อน แจ้งเราได้ทุกช่องทาง",
},
{
heading: "ความเป็นส่วนตัว",
body: "เราไม่ใช้คุกกี้เพื่อการโฆษณา และไม่เก็บ IP หรือ User-Agent ของคุณ สถิติการค้นหาถูกเก็บแบบไม่ระบุตัวตนเพื่อปรับปรุงการค้นหาเท่านั้น",
},
{
heading: "หลายภาษา",
body: "เว็บรองรับภาษาไทยและอังกฤษ สลับได้ที่มุมขวาบนของทุกหน้า และจดจำภาษาที่คุณเลือกไว้ให้อัตโนมัติ",
},
],
contactHeading: "ติดต่อและแจ้งข้อมูล",
contactNote:
"พบข้อมูลโรงหนังผิด ต้องการเพิ่มโรงใหม่ หรืออยากให้เราช่วยประชาสัมพันธ์กิจกรรม ใช้ช่องทางโซเชียลในส่วนท้ายของหน้าเว็บได้เลย",
},
list: {
title: "รายชื่อโรงหนังทุกประเภทและกลุ่มคนฉายหนัง",
showMore: "แสดงเพิ่ม",
empty: "ไม่พบโรงหนังที่ตรงกับคำค้น ลองเปลี่ยนคำหรือหมวดหมู่ดู",
},
card: {
seeDetail: "ดูรายละเอียด",
distanceFallback: "— km.",
locationFallback: "ยังไม่ระบุสถานที่",
categoryFallback: "ยังไม่ระบุประเภท",
},
detail: {
back: "ย้อนกลับ",
openMap: "เปิด Google map",
contactTitle: "สอบถามข้อมูลและจองตั๋ว",
paymentMethods: "ช่องทางชำระเงิน",
showtimes: "ดูรอบฉาย",
facilities: "สิ่งอำนวยความสะดวก",
location: "ที่ตั้ง",
otherCinemas: "โรงหนังอิสระอื่นๆ",
contactsFallback: "ยังไม่ระบุช่องทางติดต่อ",
paymentsFallback: "ยังไม่ระบุ",
addressFallback: "ยังไม่ระบุที่อยู่",
noData: "ไม่มีข้อมูล",
},
gallery: {
main: "ภาพบรรยากาศโรงหนัง",
second: "ภาพที่ 2",
third: "ภาพที่ 3",
previous: "ก่อนหน้า",
next: "ถัดไป",
more: (remaining) => `${remaining}+`,
},
notFound: {
title: "ไม่พบโรงหนังที่ค้นหา",
text: "ลิงก์อาจเปลี่ยนแล้ว กลับไปเลือกจากรายชื่อโรงหนังอิสระได้เลย",
cta: "กลับหน้าแรก",
},
categories: {
ทั้งหมด: "ทั้งหมด",
ยอดนิยม: "ยอดนิยม",
อาร์ตเฮาส์: "อาร์ตเฮาส์",
สารคดี: "สารคดี",
หนังสั้น: "หนังสั้น",
หนังคลาสสิก: "หนังคลาสสิก",
หนังนานาชาติ: "หนังนานาชาติ",
หนังนอกกระแส: "หนังนอกกระแส",
หนังในกระแส: "หนังในกระแส",
หนังฝรั่งเศส: "หนังฝรั่งเศส",
กลุ่มคนฉายหนัง: "กลุ่มคนฉายหนัง",
หนังไทย: "หนังไทย",
},
tags: {
ยอดนิยม: "ยอดนิยม",
อาร์ตเฮาส์: "อาร์ตเฮาส์",
หนังคลาสสิก: "หนังคลาสสิก",
หนังนอกกระแส: "หนังนอกกระแส",
หนังในกระแส: "หนังในกระแส",
กลุ่มคนฉายหนัง: "กลุ่มคนฉายหนัง",
หนังไทย: "หนังไทย",
},
facilities: {
seating: { title: "โซนนั่งรอ", sub: "บริเวณโถงโรงภาพยนตร์" },
ticket: { title: "จุดจำหน่ายตั๋ว", sub: "Box Office ชั้น 5" },
restaurant: { title: "ร้านอาหาร", sub: "ภายในศูนย์การค้า" },
cafe: { title: "ร้านคาเฟ่", sub: "บริเวณโถงโรงภาพยนตร์" },
garden: { title: "สวนหย่อม", sub: "ลานกลางแจ้ง" },
bookstore: { title: "ร้านหนังสือ", sub: "ภายในศูนย์การค้า" },
colearning: { title: "Co-Learning Space", sub: "บริเวณโถงโรงภาพยนตร์" },
other: { title: "อื่นๆ", sub: "ร้านทำผม ร้านทำเล็บ" },
},
transport: {
private_car: "รถยนต์ส่วนตัว",
metro: "รถไฟฟ้า",
bus: "รถประจำทาง",
},
payments: {
เงินสด: "เงินสด",
บัตรเครดิต: "บัตรเครดิต",
สแกนจ่าย: "สแกนจ่าย",
},
};
const EN: Messages = {
meta: {
homeDescription: "Find independent cinemas — an alternative way to watch films",
cinemaNotFoundTitle: "Cinema not found",
},
hero: {
titlePrefix: "Discover ",
titleHighlight: "new cinemas",
titleSuffix: " near you",
subtitle:
"Find local cinemas, indie screens and film-screening collectives — an alternative way to watch films",
},
search: {
placeholder: "Search by cinema, place / province / film genre",
nearMe: "Near me",
submit: "Search",
locating: "Locating…",
denied: "Location permission denied",
unsupported: "This device cannot share its location",
error: "Could not get your location. Try again.",
sortedByDistance: "Sorted nearest first",
},
nav: {
home: "Home",
about: "About us",
},
about: {
title: "About us",
lead: "AlterFlixHub brings Thailand's independent and arthouse cinemas together in one place, so film lovers can find the right screen and get there easily.",
sections: [
{
heading: "What we do",
body: "We list independent cinemas with the details that matter — genres, facilities, how to get there and how to reach them — plus a “Near me” button that sorts every cinema by real road distance.",
},
{
heading: "Where the data comes from",
body: "Our team maintains the listings through the admin panel. Coordinates come from OpenStreetMap and distances are calculated with OSRM. If something looks wrong, tell us on any channel.",
},
{
heading: "Privacy",
body: "No advertising cookies, and we never store your IP address or user agent. Search statistics are recorded anonymously, only to improve search results.",
},
{
heading: "Two languages",
body: "The site works in Thai and English. Switch language at the top right of any page — your choice is remembered automatically.",
},
],
contactHeading: "Contact and corrections",
contactNote:
"Spotted wrong information, want to add a cinema, or need help promoting a screening? Use the social links in the footer of any page.",
},
list: {
title: "Local cinemas, indie screens and film collectives",
showMore: "Show more",
empty: "No cinema matches that search. Try another word or category.",
},
card: {
seeDetail: "View details",
distanceFallback: "— km.",
locationFallback: "Location not specified",
categoryFallback: "Genre not specified",
},
detail: {
back: "Back",
openMap: "Open Google map",
contactTitle: "Enquiries and tickets",
paymentMethods: "Payment methods",
showtimes: "See showtimes",
facilities: "Facilities",
location: "Location",
otherCinemas: "Other independent cinemas",
contactsFallback: "No contact channel yet",
paymentsFallback: "Not specified",
addressFallback: "Address not specified",
noData: "No data",
},
gallery: {
main: "Cinema photo",
second: "Photo 2",
third: "Photo 3",
previous: "Previous",
next: "Next",
more: (remaining) => `${remaining}+`,
},
notFound: {
title: "Cinema not found",
text: "The link may have changed. Pick a cinema from the list instead.",
cta: "Back to home",
},
categories: {
ทั้งหมด: "All",
ยอดนิยม: "Popular",
อาร์ตเฮาส์: "Arthouse",
สารคดี: "Documentary",
หนังสั้น: "Short films",
หนังคลาสสิก: "Classics",
หนังนานาชาติ: "International",
หนังนอกกระแส: "Independent",
หนังในกระแส: "Mainstream",
หนังฝรั่งเศส: "French films",
กลุ่มคนฉายหนัง: "Film collectives",
หนังไทย: "Thai films",
},
tags: {
ยอดนิยม: "Popular",
อาร์ตเฮาส์: "Arthouse",
หนังคลาสสิก: "Classics",
หนังนอกกระแส: "Independent",
หนังในกระแส: "Mainstream",
กลุ่มคนฉายหนัง: "Film collectives",
หนังไทย: "Thai films",
},
facilities: {
seating: { title: "Seating area", sub: "Cinema lobby" },
ticket: { title: "Ticket counter", sub: "Box office, 5th floor" },
restaurant: { title: "Restaurants", sub: "Inside the mall" },
cafe: { title: "Cafés", sub: "Cinema lobby" },
garden: { title: "Garden", sub: "Outdoor plaza" },
bookstore: { title: "Bookstore", sub: "Inside the mall" },
colearning: { title: "Co-learning space", sub: "Cinema lobby" },
other: { title: "Others", sub: "Hair and nail salons" },
},
transport: {
private_car: "Private car",
metro: "Metro",
bus: "Bus",
},
payments: {
เงินสด: "Cash",
บัตรเครดิต: "Credit card",
สแกนจ่าย: "QR payment",
},
};
export const MESSAGES: Record<Locale, Messages> = { th: TH, en: EN };
/** แปลค่าจาก dictionary — ค่าที่ไม่รู้จักถูกส่งกลับไปตามเดิมเพื่อไม่ให้ข้อความหาย */
export function translate(
dictionary: Record<string, string>,
key: string,
): string {
return dictionary[key] ?? key;
}
export function isLocale(value: string | undefined | null): value is Locale {
return value === "th" || value === "en";
}
+100
View File
@@ -0,0 +1,100 @@
import { describe, expect, it } from "vitest";
import type { Cinema } from "@/lib/cinemas";
import { coordinatesQuery, mapEmbedUrl, mapOpenUrl, mapQueryFromUrl } from "@/lib/map-embed";
/**
* สเปกของแผนที่หน้าโรงหนัง — ลำดับ fallback ตามที่ตกลง:
* map_url → coordinates → "ไม่มีข้อมูล"
*/
function cinema(patch: Partial<Cinema> = {}): Cinema {
return {
slug: "demo",
name: "DEMO",
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
...patch,
};
}
describe("mapQueryFromUrl", () => {
it("ดึงค่า q จากลิงก์ Google Maps", () => {
expect(mapQueryFromUrl("https://maps.google.com/?q=House+Samyan")).toBe("House Samyan");
expect(mapQueryFromUrl("https://www.google.com/maps?query=Mecani")).toBe("Mecani");
});
it("ดึงพิกัดจาก /@lat,lng", () => {
expect(
mapQueryFromUrl("https://www.google.com/maps/place/X/@13.7466,100.5347,17z"),
).toBe("13.7466,100.5347");
});
it("ลิงก์ย่อแกะไม่ได้ → null (ให้ไปใช้พิกัดในหลังบ้าน)", () => {
expect(mapQueryFromUrl("https://maps.app.goo.gl/abc123")).toBeNull();
expect(mapQueryFromUrl("https://goo.gl/maps/xyz")).toBeNull();
});
it("เว็บที่ไม่ใช่แผนที่ → null", () => {
expect(mapQueryFromUrl("https://www.ilovemvp.com/")).toBeNull();
expect(mapQueryFromUrl(null)).toBeNull();
expect(mapQueryFromUrl(" ")).toBeNull();
});
});
describe("coordinatesQuery", () => {
it("คืน lat,lng เมื่อกรอกจริง", () => {
expect(
coordinatesQuery({ coordinates: { latitude: 13.7466, longitude: 100.5347 } }),
).toBe("13.7466,100.5347");
});
it("0,0 ถือว่ายังไม่กรอก", () => {
expect(coordinatesQuery({ coordinates: { latitude: 0, longitude: 0 } })).toBeNull();
expect(coordinatesQuery({ coordinates: null })).toBeNull();
});
});
describe("mapEmbedUrl", () => {
it("ใช้ map_url ก่อนพิกัด", () => {
const url = mapEmbedUrl(
cinema({
map_url: "https://maps.google.com/?q=Doc+Club",
coordinates: { latitude: 13.7, longitude: 100.5 },
}),
);
expect(url).toContain("q=Doc%20Club");
expect(url).toContain("output=embed");
});
it("ไม่มี map_url → ใช้พิกัด", () => {
const url = mapEmbedUrl(cinema({ coordinates: { latitude: 15.11, longitude: 104.32 } }));
expect(url).toContain("q=15.11%2C104.32");
});
it("ไม่มีทั้งคู่ → null (UI แสดง 'ไม่มีข้อมูล')", () => {
expect(mapEmbedUrl(cinema())).toBeNull();
});
it("ส่ง hl ตามภาษา", () => {
const url = mapEmbedUrl(cinema({ coordinates: { latitude: 1, longitude: 2 } }), "en");
expect(url).toContain("hl=en");
});
});
describe("mapOpenUrl", () => {
it("คืนลิงก์เปิดแผนที่ หรือ null", () => {
expect(mapOpenUrl(cinema({ coordinates: { latitude: 1, longitude: 2 } }))).toContain(
"maps.google.com/?q=1%2C2",
);
expect(mapOpenUrl(cinema())).toBeNull();
});
});
+69
View File
@@ -0,0 +1,69 @@
import type { Cinema } from "@/lib/cinemas";
import type { Locale } from "@/lib/i18n/messages";
/**
* URL สำหรับฝังแผนที่ Google Maps ในหน้าเว็บ (ไม่ต้องใช้ API key)
*
* ลำดับการเลือกตำแหน่ง:
* 1. `map_url` ของโรงหนัง — ดึงค่า q / ll / พิกัดในลิงก์มาใช้
* 2. `coordinates` ที่กรอกในหลังบ้าน
* 3. ไม่มีทั้งคู่ → null (ให้ UI แสดง "ไม่มีข้อมูล")
*/
/** แกะคำค้น/พิกัดออกจากลิงก์ Google Maps ที่ผู้ใช้กรอก */
export function mapQueryFromUrl(url: string | null | undefined): string | null {
const value = (url ?? "").trim();
if (!value) return null;
// ลิงก์ย่อ (maps.app.goo.gl / goo.gl/maps) แกะพิกัดไม่ได้ → ปล่อยให้ไปใช้พิกัดในหลังบ้าน
if (/(?:maps\.app\.goo\.gl|goo\.gl\/maps)/i.test(value)) return null;
try {
const parsed = new URL(value);
const query =
parsed.searchParams.get("q") ??
parsed.searchParams.get("query") ??
parsed.searchParams.get("ll");
if (query && query.trim()) return query.trim();
} catch {
// ไม่ใช่ URL เต็ม — ลองใช้ regex ด้านล่างต่อ
}
const at = value.match(/@(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)/);
if (at) return `${at[1]},${at[2]}`;
const place = value.match(/\/place\/(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)/);
if (place) return `${place[1]},${place[2]}`;
return null;
}
/** คำค้นจากพิกัดในหลังบ้าน (null ถ้ายังไม่กรอก) */
export function coordinatesQuery(
cinema: Pick<Cinema, "coordinates">,
): string | null {
const coords = cinema.coordinates;
if (!coords) return null;
const { latitude, longitude } = coords;
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
// 0,0 คือค่าเริ่มต้นที่ยังไม่ได้กรอกจริง
if (latitude === 0 && longitude === 0) return null;
return `${latitude},${longitude}`;
}
/** URL ฝังแผนที่ หรือ null เมื่อไม่มีข้อมูลตำแหน่งเลย */
export function mapEmbedUrl(
cinema: Cinema,
locale: Locale = "th",
): string | null {
const query = mapQueryFromUrl(cinema.map_url) ?? coordinatesQuery(cinema);
if (!query) return null;
return `https://maps.google.com/maps?q=${encodeURIComponent(query)}&z=16&hl=${locale}&output=embed`;
}
/** ลิงก์เปิดใน Google Maps (ให้ผู้ใช้กดดูเต็มจอ) */
export function mapOpenUrl(cinema: Cinema): string | null {
const query = mapQueryFromUrl(cinema.map_url) ?? coordinatesQuery(cinema);
if (!query) return null;
return `https://maps.google.com/?q=${encodeURIComponent(query)}`;
}
+102
View File
@@ -0,0 +1,102 @@
import { readEvents } from "@/lib/analytics.server";
/**
* อันดับ "ยอดนิยม" จากสถิติผู้เข้าชมจริง (ไม่ใช่ป้ายที่คนตั้งเอง)
*
* กติกา:
* - ต้องมีประวัติข้อมูลอย่างน้อย 6 เดือน (180 วัน) ก่อน ถึงจะเริ่มจัดอันดับ
* เพื่อไม่ให้โรงที่เพิ่งถูกเปิดดู 2-3 ครั้งครองอันดับจากฐานผู้ชมที่ยังเล็ก
* - คะแนน: cinema_view = 1, cinema_select = 1.5 (เจตนาชัดกว่า), คูณ decay
* ครึ่งชีวิต 30 วัน และนับเฉพาะ event ภายใน 90 วันล่าสุด
*/
export const POPULARITY_MIN_HISTORY_DAYS = 180; // 6 เดือน
export const POPULARITY_WINDOW_DAYS = 90;
export const POPULARITY_TOP_N = 8;
const DAY_MS = 24 * 60 * 60 * 1000;
const SELECT_WEIGHT = 1.5;
const HALF_LIFE_DAYS = 30;
export type PopularityScore = {
slug: string;
score: number;
views: number;
selects: number;
};
export type PopularityState = {
/** true = มีข้อมูลครบ 6 เดือนแล้ว ใช้จัดอันดับได้ */
ready: boolean;
/** จำนวนวันของข้อมูลที่มีอยู่จริง */
history_days: number;
/** วันที่ยังต้องเก็บเพิ่ม (0 = ครบแล้ว) */
days_remaining: number;
window_days: number;
total_events: number;
/** เรียงจากมากไปน้อย (ว่างเมื่อ ready=false) */
ranking: PopularityScore[];
/** slug ที่ติดอันดับ (ว่างเมื่อ ready=false) */
slugs: string[];
computed_at: string;
};
let cache: { state: PopularityState; expires: number } | null = null;
const CACHE_MS = 5 * 60 * 1000;
/** คำนวณสถานะ/อันดับยอดนิยม (memo 5 นาที) */
export async function computePopularity(now = Date.now()): Promise<PopularityState> {
if (cache && cache.expires > now) return cache.state;
const events = await readEvents();
let earliest = Number.POSITIVE_INFINITY;
const buckets = new Map<string, { views: number; selects: number; score: number }>();
const windowStart = now - POPULARITY_WINDOW_DAYS * DAY_MS;
for (const event of events) {
const at = Date.parse(event.at);
if (!Number.isFinite(at)) continue;
if (at < earliest) earliest = at;
if (at < windowStart) continue;
if (!event.slug) continue;
if (event.type !== "cinema_view" && event.type !== "cinema_select") continue;
const ageDays = Math.max(0, (now - at) / DAY_MS);
const decay = 0.5 ** (ageDays / HALF_LIFE_DAYS);
const weight = (event.type === "cinema_view" ? 1 : SELECT_WEIGHT) * decay;
const bucket = buckets.get(event.slug) ?? { views: 0, selects: 0, score: 0 };
if (event.type === "cinema_view") bucket.views += 1;
else bucket.selects += 1;
bucket.score += weight;
buckets.set(event.slug, bucket);
}
const historyDays = Number.isFinite(earliest)
? Math.floor((now - earliest) / DAY_MS)
: 0;
const ready = historyDays >= POPULARITY_MIN_HISTORY_DAYS;
const ranking: PopularityScore[] = [...buckets.entries()]
.map(([slug, bucket]) => ({
slug,
score: Math.round(bucket.score * 100) / 100,
views: bucket.views,
selects: bucket.selects,
}))
.sort((a, b) => b.score - a.score || b.views - a.views || a.slug.localeCompare(b.slug));
const state: PopularityState = {
ready,
history_days: historyDays,
days_remaining: Math.max(0, POPULARITY_MIN_HISTORY_DAYS - historyDays),
window_days: POPULARITY_WINDOW_DAYS,
total_events: events.length,
ranking: ready ? ranking.slice(0, POPULARITY_TOP_N) : [],
slugs: ready ? ranking.slice(0, POPULARITY_TOP_N).map((item) => item.slug) : [],
computed_at: new Date(now).toISOString(),
};
cache = { state, expires: now + CACHE_MS };
return state;
}
+94
View File
@@ -0,0 +1,94 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AnalyticsEvent } from "@/lib/analytics-types";
/**
* สเปกของอันดับ "ยอดนิยม" — ต้องไม่จัดอันดับก่อนมีข้อมูลครบ 6 เดือน
*/
const readEventsMock = vi.fn<() => Promise<AnalyticsEvent[]>>();
vi.mock("@/lib/analytics.server", () => ({
readEvents: () => readEventsMock(),
appendEvent: async () => {},
}));
const DAY = 24 * 60 * 60 * 1000;
const NOW = Date.parse("2026-11-01T00:00:00.000Z");
function event(daysAgo: number, type: AnalyticsEvent["type"], slug: string): AnalyticsEvent {
return {
type,
at: new Date(NOW - daysAgo * DAY).toISOString(),
visitor: "v",
locale: "th",
slug,
};
}
async function compute(events: AnalyticsEvent[]) {
readEventsMock.mockResolvedValue(events);
vi.resetModules();
const { computePopularity } = await import("@/lib/popularity.server");
return computePopularity(NOW);
}
describe("computePopularity", () => {
beforeEach(() => {
readEventsMock.mockReset();
});
it("ข้อมูลแค่ 2 วัน → ready=false และไม่คืนอันดับ", async () => {
const state = await compute([event(2, "cinema_view", "a"), event(1, "cinema_view", "b")]);
expect(state.ready).toBe(false);
expect(state.slugs).toEqual([]);
expect(state.history_days).toBe(2);
expect(state.days_remaining).toBe(178);
});
it("ข้อมูลครบ 180 วัน → ready=true และเริ่มจัดอันดับ", async () => {
const state = await compute([
event(200, "cinema_view", "old"), // เก่ากว่า 6 เดือน = ใช้เป็นหลักฐานประวัติ
event(10, "cinema_view", "a"),
event(10, "cinema_view", "a"),
event(9, "cinema_select", "b"),
]);
expect(state.ready).toBe(true);
expect(state.slugs).toEqual(["a", "b"]);
expect(state.days_remaining).toBe(0);
});
it("event เก่ากว่า 90 วันไม่ถูกนับคะแนน แต่ยังนับประวัติ", async () => {
const state = await compute([
event(200, "cinema_view", "long-ago"),
event(1, "cinema_view", "fresh"),
]);
expect(state.ready).toBe(true);
expect(state.slugs).toEqual(["fresh"]);
});
it("cinema_select ได้น้ำหนักมากกว่า cinema_view", async () => {
const state = await compute([
event(200, "cinema_view", "seed"),
event(1, "cinema_view", "viewed"),
event(1, "cinema_select", "clicked"),
]);
expect(state.slugs[0]).toBe("clicked");
});
it("ไม่นับ event ที่ไม่มี slug (เช่น search/near_me)", async () => {
const state = await compute([
event(200, "cinema_view", "seed"),
{ type: "search", at: new Date(NOW).toISOString(), visitor: "v", locale: "th", query: "x" },
{ type: "near_me", at: new Date(NOW).toISOString(), visitor: "v", locale: "th" },
]);
expect(state.slugs).toEqual([]);
});
it("ไม่มีข้อมูลเลย → history 0 วัน", async () => {
const state = await compute([]);
expect(state.ready).toBe(false);
expect(state.history_days).toBe(0);
expect(state.total_events).toBe(0);
});
});
+3
View File
@@ -0,0 +1,3 @@
import { getBrowserTabId } from "@agent-native/core/client/hooks";
export const TAB_ID = getBrowserTabId();
+1
View File
@@ -0,0 +1 @@
export { cn } from "@agent-native/toolkit/utils";
+115
View File
@@ -0,0 +1,115 @@
import { configureTracking } from "@agent-native/core/client/analytics";
import { appPath } from "@agent-native/core/client/api-path";
import { useDbSync } from "@agent-native/core/client/hooks";
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 { Links, Meta, Outlet, Scripts, ScrollRestoration, useLoaderData, useRouteLoaderData } from "react-router";
import type { LinksFunction } from "react-router";
import { Layout as AppLayout } from "@/components/layout/Layout";
import { AppToolkitProvider } from "@/components/ui/toolkit-provider";
import { useNavigationState } from "@/hooks/use-navigation-state";
import { NearMeProvider } from "@/hooks/use-near-me";
import { APP_NAME, APP_TITLE } from "@/lib/app-config";
import { ContentProvider } from "@/lib/content-context";
import { readContent } from "@/lib/content.server";
import { LocaleProvider, readLocaleFromRequestUrl } from "@/lib/i18n";
import { TAB_ID } from "@/lib/tab-id";
import stylesheet from "./global.css?url";
configureTracking({
getDefaultProps: (_name, properties) => ({
...properties,
app: APP_NAME,
}),
});
export const links: LinksFunction = () => [
{ rel: "stylesheet", href: stylesheet },
];
const THEME_INIT_SCRIPT = getThemeInitScript();
/** เนื้อหาที่แก้ได้จากหลังบ้าน (โรงหนัง/คำศัพท์/footer) โหลดครั้งเดียวที่ root */
export async function loader({ request }: { request: Request }) {
const content = await readContent();
return { content, localeFromUrl: readLocaleFromRequestUrl(request) };
}
export function Layout({ children }: { children: React.ReactNode }) {
const data = useRouteLoaderData<typeof loader>("root");
const lang = data?.localeFromUrl === "en" ? "en" : "th";
return (
<html lang={lang} suppressHydrationWarning>
<head>
<meta charSet="utf-8" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
<script
suppressHydrationWarning
dangerouslySetInnerHTML={{ __html: THEME_INIT_SCRIPT }}
/>
{/* guard:allow-raw-color - theme-color metadata requires a concrete browser-chrome color. */}
<meta name="theme-color" content="#18181B" />
<meta name="mobile-web-app-capable" content="yes" />
<meta
name="apple-mobile-web-app-status-bar-style"
content="black-translucent"
/>
<meta name="apple-mobile-web-app-title" content={APP_TITLE} />
<link rel="icon" type="image/svg+xml" href={appPath("/favicon.svg")} />
<link rel="apple-touch-icon" href={appPath("/icon-180.svg")} />
<Meta />
<Links />
</head>
<body>
{children}
<ScrollRestoration />
<Scripts />
</body>
</html>
);
}
function DbSyncSetup() {
const qc = useQueryClient();
useNavigationState();
useDbSync({
queryClient: qc,
ignoreSource: TAB_ID,
});
return null;
}
export default function Root() {
const [queryClient] = useState(() => createAgentNativeQueryClient());
const { content, localeFromUrl } = useLoaderData<typeof loader>();
return (
<ContentProvider content={content}>
<LocaleProvider
initialLocale={localeFromUrl === "en" ? "en" : "th"}
localeFromUrl={localeFromUrl}
terms={content.site.terms}
>
<NearMeProvider cinemas={content.cinemas}>
<AppToolkitProvider>
<AppProviders queryClient={queryClient}>
<DbSyncSetup />
<AppLayout>
<Outlet />
</AppLayout>
</AppProviders>
</AppToolkitProvider>
</NearMeProvider>
</LocaleProvider>
</ContentProvider>
);
}
export { ErrorBoundary } from "@agent-native/toolkit/app/shared";
+6
View File
@@ -0,0 +1,6 @@
import { type RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export default flatRoutes({
ignoredRouteFiles: ["**/*.test.{ts,tsx}", "**/*.spec.{ts,tsx}"],
}) satisfies RouteConfig;
+144
View File
@@ -0,0 +1,144 @@
import { useEffect, useMemo, useState } from "react";
import { useLoaderData } from "react-router";
import { HeroSection } from "@/components/home/HeroSection";
import { CategoryFilter, CinemaGrid } from "@/components/site/CinemaGrid";
import { SiteShell } from "@/components/site/SiteShell";
import { useNearMe } from "@/hooks/use-near-me";
import { trackEvent } from "@/lib/analytics-client";
import { APP_TITLE } from "@/lib/app-config";
import { filterCinemas, CINEMA_CATEGORIES, DEFAULT_CATEGORY, publiclyVisible, type Cinema, type CinemaCategory } from "@/lib/cinemas";
import { dailyOrder, dayKey } from "@/lib/daily-order";
import { computePopularity } from "@/lib/popularity.server";
import { useContent } from "@/lib/content-context";
import { sortByDistance } from "@/lib/geo";
import { useI18n } from "@/lib/i18n";
import { DEFAULT_LOCALE, MESSAGES } from "@/lib/i18n/messages";
/** head (title/description) ไม่เปลี่ยนตามภาษา — meta() ไม่มี access ต่อ cookie */
const HEAD_MESSAGES = MESSAGES[DEFAULT_LOCALE];
export function meta() {
return [
{ title: APP_TITLE },
{ name: "description", content: HEAD_MESSAGES.meta.homeDescription },
];
}
/** จำนวนการ์ดที่แสดงก่อนกด "แสดงเพิ่ม" */
const INITIAL_VISIBLE = 4;
/** อันดับยอดนิยม + คีย์วันที่สำหรับสลับลำดับการ์ด (memo 5 นาที) — ส่งมากับ loader */
export async function loader() {
return { popularity: await computePopularity(), orderKey: dayKey() };
}
export default function HomeRoute() {
const { messages, locale } = useI18n();
const { popularity, orderKey } = useLoaderData<typeof loader>();
const { cinemas } = useContent();
const { status: nearMeStatus, distances, requestLocation } = useNearMe();
const [category, setCategory] = useState<CinemaCategory>(DEFAULT_CATEGORY);
const [query, setQuery] = useState("");
const [showAll, setShowAll] = useState(false);
const matched = useMemo(() => {
// ลำดับการ์ดสลับทุกวัน (ไม่ให้โรงใดอยู่ตำแหน่งเดิมสองวันติดกัน)
const base = dailyOrder(publiclyVisible(cinemas), (cinema) => cinema.slug, orderKey);
const byStats =
category === "ยอดนิยม" && popularity.ready && query.trim() === "";
if (!byStats) return filterCinemas(base, { category, query });
// ใช้เฉพาะโรงที่ยังไม่ถูกซ่อน และเรียงตามอันดับสถิติ
const bySlug = new Map(base.map((cinema) => [cinema.slug, cinema]));
return popularity.slugs
.map((slug) => bySlug.get(slug))
.filter((cinema): cinema is Cinema => cinema !== undefined);
}, [cinemas, category, query, popularity, orderKey]);
// เรียงจากใกล้สุดไปไกลสุดเมื่อทราบตำแหน่งแล้ว (ไม่กรองตามรัศมี — ไกลแค่ไหนก็ยังแสดง)
const ordered =
nearMeStatus === "ready" ? sortByDistance(matched, distances) : matched;
const visibleCinemas = showAll ? ordered : ordered.slice(0, INITIAL_VISIBLE);
const hasMore = ordered.length > visibleCinemas.length;
const keyword = query.trim();
// เก็บสถิติการค้นหา: ยิงครั้งเดียวหลังผู้ใช้หยุดพิมพ์ 900ms และมีคำค้นอย่างน้อย 2 ตัวอักษร
useEffect(() => {
if (keyword.length < 2) return;
const timer = setTimeout(() => {
trackEvent({
type: "search",
query: keyword,
category,
result_count: matched.length,
locale,
});
}, 900);
return () => clearTimeout(timer);
}, [keyword, category, matched.length, locale]);
function handleRequestLocation() {
requestLocation();
trackEvent({
type: "near_me",
category,
query: keyword || undefined,
result_count: matched.length,
locale,
});
}
return (
<SiteShell variant="home">
<main className="relative z-10 mx-auto max-w-[1440px] px-5 pb-12 md:px-[108px] md:pb-16">
<HeroSection
query={query}
onQueryChange={setQuery}
nearMeStatus={nearMeStatus}
onRequestLocation={handleRequestLocation}
/>
<section className="mt-16 flex flex-col gap-6 md:mt-[65px]">
<div className="flex min-h-[72px] items-center border-b border-[#1F1F1F] py-2">
<h2 className="text-[28px] font-semibold leading-[1.3]">
{messages.list.title}
</h2>
</div>
<CategoryFilter
active={category}
categories={CINEMA_CATEGORIES}
onChange={setCategory}
/>
{visibleCinemas.length === 0 ? (
<p className="py-16 text-center text-sm text-[#B3B3B3]">
{messages.list.empty}
</p>
) : (
<div className="mt-2">
<CinemaGrid
cinemas={visibleCinemas}
source={keyword ? "search" : "category"}
searchQuery={keyword || undefined}
/>
</div>
)}
{hasMore ? (
<div className="flex justify-center pt-2">
<button
type="button"
onClick={() => setShowAll(true)}
className="h-10 w-[200px] rounded-lg border border-[#8F0808] bg-[#8F0808] transition hover:bg-[#a30a0a]"
>
{messages.list.showMore}
</button>
</div>
) : null}
</section>
</main>
</SiteShell>
);
}
+121
View File
@@ -0,0 +1,121 @@
import { IconArrowBackUp } from "@tabler/icons-react";
import { Link } from "react-router";
import { SiteShell } from "@/components/site/SiteShell";
import { footerIcon } from "@/components/site/footer-icons";
import { APP_TITLE } from "@/lib/app-config";
import { useContent } from "@/lib/content-context";
import { COLORS } from "@/lib/design-tokens";
import { useI18n } from "@/lib/i18n";
import { DEFAULT_LOCALE, MESSAGES } from "@/lib/i18n/messages";
const HEAD_MESSAGES = MESSAGES[DEFAULT_LOCALE];
export function meta() {
return [
{ title: `${HEAD_MESSAGES.about.title} — ${APP_TITLE}` },
{ name: "description", content: HEAD_MESSAGES.about.lead },
];
}
/**
* หน้า "เกี่ยวกับเรา" — เนื้อหามาจากหลังบ้าน (data/content) แยกตามภาษา
* ภาษาภาพเดียวกับหน้าแรก/หน้ารายละเอียด: กรอบ 1440 + px-[108px], การ์ดขอบโทน #332B2B,
* chip แดง, ตัวเลขในวงกลมไล่แสง (glowSoft) และไอคอนโซเชียลชุดเดียวกับ footer
*/
export default function AboutRoute() {
const { messages, locale } = useI18n();
const { site, about } = useContent();
const content = about[locale];
return (
<SiteShell variant="detail">
<main className="relative z-10 mx-auto flex w-full max-w-[1440px] flex-col gap-10 px-5 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} />
{messages.nav.home}
</Link>
<header className="flex flex-col gap-4">
<h1 className="text-[32px] font-bold leading-[1.3] md:text-[40px]">
{content.title}
</h1>
<p className="font-content max-w-[860px] text-[19px] leading-[1.8] text-[#C4C4C4] md:text-[21px]">
{content.lead}
</p>
</header>
<section className="gap-6 lg:columns-2">
{content.sections.map((section, index) => (
<article
key={`${section.heading}-${index}`}
className="mb-8 flex break-inside-avoid flex-col gap-5 rounded-xl bg-[#1B1B1B]/70 p-7 backdrop-blur-sm transition hover:bg-[#1B1B1B] md:p-8"
style={{ border: `1px solid ${COLORS.border}` }}
>
<div className="flex items-center gap-3">
<span
className="flex size-12 shrink-0 items-center justify-center rounded-full text-sm font-semibold text-[#D47272]"
style={{
background: "rgba(143,8,8,0.16)",
border: "1px solid rgba(169,38,38,0.45)",
}}
aria-hidden="true"
>
{String(index + 1).padStart(2, "0")}
</span>
<h2 className="text-2xl font-semibold leading-[1.3]">
{section.heading}
</h2>
</div>
<p className="font-content text-[17px] leading-[1.95] text-[#C7C7C7] md:text-[18px]">
{section.body}
</p>
</article>
))}
</section>
<section
className="flex flex-col gap-6 rounded-xl p-6 backdrop-blur-sm lg:flex-row lg:items-center lg:justify-between"
style={{
border: "1px solid rgba(169,38,38,0.45)",
background:
"linear-gradient(180deg, rgba(143,8,8,0.18) 0%, rgba(27,27,27,0.85) 65%, rgba(13,13,13,0.7) 100%)",
}}
>
<div className="flex flex-col gap-3">
<h2 className="text-2xl font-semibold leading-[1.3]">
{content.contactHeading}
</h2>
<p className="font-content max-w-[720px] text-[16px] leading-[1.9] text-[#C4C4C4] md:text-[17px]">
{content.contactNote}
</p>
</div>
{site.footer.length > 0 ? (
<div className="flex flex-wrap items-center gap-2">
{site.footer.map((item) => {
const Icon = footerIcon(item.icon_name);
return (
<a
key={item.id}
href={item.href}
aria-label={item.label}
title={item.label}
target="_blank"
rel="noreferrer"
className="flex size-11 items-center justify-center rounded-full bg-white/90 text-[#0D0D0D] transition hover:bg-white"
>
<Icon size={20} />
</a>
);
})}
</div>
) : null}
</section>
</main>
</SiteShell>
);
}
+1221
View File
File diff suppressed because it is too large. Load diff
+86
View File
@@ -0,0 +1,86 @@
import { useState } from "react";
import { useNavigate } from "react-router";
const inputClass =
"w-full rounded-lg border border-[#303030] bg-[#141414] px-3 py-2 text-sm text-white outline-none focus:border-[#A92626]";
export default function AdminLoginRoute() {
const navigate = useNavigate();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
async function submit(event: React.FormEvent) {
event.preventDefault();
setBusy(true);
setError(null);
try {
const response = await fetch("/api/admin/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ username, password }),
});
if (!response.ok) {
const payload = (await response.json().catch(() => ({}))) as {
statusMessage?: string;
message?: string;
};
setError(payload.statusMessage ?? payload.message ?? "เข้าสู่ระบบไม่สำเร็จ");
return;
}
navigate("/admin");
} catch {
setError("เชื่อมต่อเซิร์ฟเวอร์ไม่ได้");
} finally {
setBusy(false);
}
}
return (
<div className="flex min-h-screen items-center justify-center bg-[#0D0D0D] px-5 text-white">
<form
onSubmit={submit}
className="w-full max-w-sm rounded-2xl border border-[#303030] bg-[#141414] p-6"
>
<h1 className="text-2xl font-semibold">เข้าสู่ระบบหลังบ้าน</h1>
<p className="mt-1 text-sm text-[#999]">AlterFlixHub · เฉพาะผู้ดูแล</p>
<label className="mt-6 block text-sm text-[#B3B3B3]">
ชื่อผู้ใช้
<input
value={username}
onChange={(event) => setUsername(event.target.value)}
autoComplete="username"
className={`mt-1 ${inputClass}`}
/>
</label>
<label className="mt-4 block text-sm text-[#B3B3B3]">
รหัสผ่าน
<input
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
autoComplete="current-password"
className={`mt-1 ${inputClass}`}
/>
</label>
{error ? (
<p role="alert" className="mt-4 text-sm text-[#D47272]">
{error}
</p>
) : null}
<button
type="submit"
disabled={busy}
className="mt-6 h-10 w-full rounded-lg bg-[#8F0808] text-sm font-medium transition hover:bg-[#a30a0a] disabled:opacity-60"
>
{busy ? "กำลังเข้าสู่ระบบ…" : "เข้าสู่ระบบ"}
</button>
</form>
</div>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { useEffect } from "react";
import { IconArrowBackUp } from "@tabler/icons-react";
import { Link, useParams } from "react-router";
import { CinemaNotFound } from "@/components/cinema/CinemaNotFound";
import { CinemaSummary } from "@/components/cinema/CinemaSummary";
import { ContactPanel } from "@/components/cinema/ContactPanel";
import { FacilitiesSection } from "@/components/cinema/FacilitiesSection";
import { Gallery } from "@/components/cinema/Gallery";
import { TransportList } from "@/components/cinema/TransportList";
import { CinemaGrid } from "@/components/site/CinemaGrid";
import { SiteShell } from "@/components/site/SiteShell";
import { useNearMe } from "@/hooks/use-near-me";
import { APP_TITLE } from "@/lib/app-config";
import { findCinemaBySlug, listOtherCinemas } from "@/lib/cinemas";
import { readContent } from "@/lib/content.server";
import { useContent } from "@/lib/content-context";
import { trackEvent } from "@/lib/analytics-client";
import { sortByDistance } from "@/lib/geo";
import { useI18n } from "@/lib/i18n";
import { DEFAULT_LOCALE, MESSAGES } from "@/lib/i18n/messages";
/** head (title) ไม่เปลี่ยนตามภาษา — meta() ไม่มี access ต่อ cookie */
const HEAD_MESSAGES = MESSAGES[DEFAULT_LOCALE];
/** อ่านชื่อโรงหนังฝั่งเซิร์ฟเวอร์ เพื่อให้ <title> ถูกตั้งแต่ HTML แรก */
export async function loader({ params }: { params: { slug?: string } }) {
const content = await readContent();
const cinema = findCinemaBySlug(content.cinemas, params.slug);
return { name: cinema ? cinema.name : null };
}
export function meta({ loaderData }: { loaderData?: { name?: string | null } }) {
const name = loaderData?.name ?? null;
return [
{
title: name
? `${name} — ${APP_TITLE}`
: `${HEAD_MESSAGES.meta.cinemaNotFoundTitle} — ${APP_TITLE}`,
},
];
}
export default function CinemaDetailRoute() {
const { messages, locale } = useI18n();
const { cinemas } = useContent();
const { status: nearMeStatus, distances } = useNearMe();
const { slug } = useParams();
const cinema = findCinemaBySlug(cinemas, slug);
// เก็บสถิติการเปิดดูหน้ารายละเอียด (ต้องอยู่ก่อน early return เพื่อให้ hook เรียกทุกครั้ง)
useEffect(() => {
if (!cinema) return;
trackEvent({ type: "cinema_view", slug: cinema.slug, locale });
}, [cinema, locale]);
if (!cinema) return <CinemaNotFound />;
const otherCinemas = listOtherCinemas(cinemas, cinema.slug);
const orderedOthers =
nearMeStatus === "ready"
? sortByDistance(otherCinemas, distances)
: otherCinemas;
return (
<SiteShell variant="detail">
<main className="relative z-10 mx-auto flex w-full max-w-[1440px] flex-col gap-10 px-5 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"
>
<IconArrowBackUp size={24} />
{messages.detail.back}
</Link>
<Gallery photos={cinema.photos} cinemaName={cinema.name} />
<section className="grid gap-10 lg:grid-cols-[minmax(0,749px)_minmax(0,384px)] lg:justify-between">
<div className="flex flex-col gap-12">
<CinemaSummary cinema={cinema} />
<TransportList transport={cinema.transport} />
</div>
<ContactPanel cinema={cinema} />
</section>
<FacilitiesSection cinema={cinema} />
<section className="flex flex-col gap-8">
<h2 className="text-2xl font-semibold leading-[1.3]">
{messages.detail.otherCinemas}
</h2>
<CinemaGrid cinemas={orderedOthers} source="other_cinemas" />
</section>
</main>
</SiteShell>
);
}
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="vite/client" />
declare module "react-dom/server.browser" {
export * from "react-dom/server";
export { default } from "react-dom/server";
}