reboot alterflixhub
This commit is contained in:
commit
1e84023a44
188 files changed
+31629
No files matched your search
@@ -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: "ต้องเข้าสู่ระบบก่อน" });
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
// ไม่ทำอะไร — ปล่อยให้หน้าเว็บทำงานต่อ
|
||||
}
|
||||
}
|
||||
@@ -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 }>;
|
||||
};
|
||||
@@ -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 !== ""),
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
@@ -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>;
|
||||
};
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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),
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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;
|
||||
});
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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-ใหม่");
|
||||
});
|
||||
});
|
||||
@@ -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";
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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)}`;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
import { getBrowserTabId } from "@agent-native/core/client/hooks";
|
||||
|
||||
export const TAB_ID = getBrowserTabId();
|
||||
@@ -0,0 +1 @@
|
||||
export { cn } from "@agent-native/toolkit/utils";
|
||||
Reference in new issue
Block a user