reboot alterflixhub

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

No files matched your search

+164
View File
@@ -0,0 +1,164 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState,
type ReactNode,
} from "react";
import {
DEFAULT_LOCALE,
MESSAGES,
isLocale,
type Locale,
type Messages,
} from "@/lib/i18n/messages";
import { applyTerms } from "@/lib/i18n/merge";
import type { TermEntry } from "@/lib/content-types";
export const LOCALE_COOKIE = "locale";
export const LOCALE_STORAGE_KEY = "alterflixhub.locale";
const LOCALE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365;
export type I18nValue = {
locale: Locale;
messages: Messages;
setLocale: (locale: Locale) => void;
};
const I18nContext = createContext<I18nValue | null>(null);
type LocaleSources = {
/** ค่าจาก query string ?lang= (ชนะทุกอย่าง) */
urlLocale?: string | null;
/** ค่าที่เก็บใน localStorage */
stored?: string | null;
/** ค่าจาก cookie */
cookie?: string | null;
};
/**
* เลือกภาษาเริ่มต้นตามลำดับ: ?lang= → localStorage → cookie → ค่าเริ่มต้น (ไทย)
* ตั้งใจไม่ใช้ navigator.language เพราะเว็บนี้เป็นไทย-first
* (ผู้ใช้ที่ต้องการอังกฤษเลือกเองได้ หรือส่งลิงก์ ?lang=en)
*/
export function resolveInitialLocale({
urlLocale,
stored,
cookie,
}: LocaleSources): Locale {
if (isLocale(urlLocale ?? null)) return urlLocale as Locale;
if (isLocale(stored ?? null)) return stored as Locale;
if (isLocale(cookie ?? null)) return cookie as Locale;
return DEFAULT_LOCALE;
}
function readCookieLocale(): string | null {
const match = document.cookie.match(
new RegExp(`(?:^|;\\s*)${LOCALE_COOKIE}=([^;]+)`),
);
return match?.[1] ?? null;
}
function readStoredLocale(): string | null {
try {
return window.localStorage.getItem(LOCALE_STORAGE_KEY);
} catch {
return null;
}
}
export function LocaleProvider({
initialLocale = DEFAULT_LOCALE,
localeFromUrl = null,
terms = [],
children,
}: {
initialLocale?: Locale;
/** ค่า ?lang= ที่ loader อ่านจาก request (ถ้ามี) */
localeFromUrl?: string | null;
terms?: TermEntry[];
children: ReactNode;
}) {
const [locale, setLocaleState] = useState<Locale>(initialLocale);
// loader ของ agent-native ไม่ส่ง cookie เข้ามา จึงอ่านแหล่งอื่นหลัง mount
// (?lang= ถูกส่งมาแล้วทาง initialLocale/localeFromUrl)
useEffect(() => {
const resolved = resolveInitialLocale({
urlLocale: localeFromUrl,
stored: readStoredLocale(),
cookie: readCookieLocale(),
});
setLocaleState((current) => (current === resolved ? current : resolved));
// ตั้งใจให้ทำงานครั้งเดียวตอน mount
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const setLocale = useCallback((next: Locale) => {
setLocaleState(next);
document.cookie = `${LOCALE_COOKIE}=${next}; path=/; max-age=${LOCALE_MAX_AGE_SECONDS}; samesite=lax`;
try {
window.localStorage.setItem(LOCALE_STORAGE_KEY, next);
} catch {
// โหมดที่บล็อก storage — cookie ยังทำงานแทน
}
}, []);
// เปิดหลายแท็บแล้วสลับภาษาที่แท็บหนึ่ง ให้แท็บอื่นตามด้วย
useEffect(() => {
function handleStorage(event: StorageEvent) {
if (event.key !== LOCALE_STORAGE_KEY || !isLocale(event.newValue)) return;
setLocaleState(event.newValue);
}
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, []);
useEffect(() => {
document.documentElement.lang = locale;
}, [locale]);
const value = useMemo<I18nValue>(
() => ({
locale,
messages: applyTerms(MESSAGES[locale], terms, locale),
setLocale,
}),
[locale, setLocale, terms],
);
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}
export function useI18n(): I18nValue {
const value = useContext(I18nContext);
if (!value) throw new Error("useI18n ต้องถูกใช้ภายใน <LocaleProvider>");
return value;
}
/** อ่านภาษาจาก cookie header — ใช้ได้ทั้งใน browser และ server */
export function readLocaleFromCookieHeader(cookieHeader: string | null): Locale {
if (!cookieHeader) return DEFAULT_LOCALE;
const match = cookieHeader.match(
new RegExp(`(?:^|;\\s*)${LOCALE_COOKIE}=([^;]+)`),
);
const value = match?.[1];
return isLocale(value) ? value : DEFAULT_LOCALE;
}
/** ?lang=th|en จาก URL ของ request (ใช้ใน loader ของ root) */
export function readLocaleFromRequestUrl(request: Request): string | null {
try {
const value = new URL(request.url).searchParams.get("lang");
return isLocale(value) ? value : null;
} catch {
return null;
}
}
export function resolveLocaleFromRequest(request: Request): Locale {
return readLocaleFromCookieHeader(request.headers.get("cookie"));
}
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from "vitest";
import { resolveInitialLocale } from "./index";
describe("resolveInitialLocale", () => {
it("?lang= ชนะทุกแหล่ง", () => {
expect(resolveInitialLocale({ urlLocale: "en", stored: "th", cookie: "th" })).toBe("en");
expect(resolveInitialLocale({ urlLocale: "th", stored: "en", cookie: "en" })).toBe("th");
});
it("ใช้ค่าที่เคยเลือก (localStorage) ก่อน cookie", () => {
expect(resolveInitialLocale({ stored: "en", cookie: "th" })).toBe("en");
});
it("ถ้าไม่มีใน localStorage ใช้ cookie", () => {
expect(resolveInitialLocale({ cookie: "en" })).toBe("en");
});
it("ไม่เคยเลือกเลย → ไทย (ไทย-first ไม่อิงภาษาของเบราว์เซอร์)", () => {
expect(resolveInitialLocale({})).toBe("th");
});
it("ค่าที่ไม่รู้จักถูกมองข้ามแล้วตกไปค่าเริ่มต้น", () => {
expect(resolveInitialLocale({ urlLocale: "fr", stored: "xx", cookie: null })).toBe("th");
});
});
+55
View File
@@ -0,0 +1,55 @@
import type { Messages } from "@/lib/i18n/messages";
import type { TermEntry } from "@/lib/content-types";
/** clone แบบคงฟังก์ชันไว้ (Messages มีฟังก์ชันเช่น gallery.more — structuredClone ใช้ไม่ได้) */
function cloneMessages<T>(value: T): T {
if (Array.isArray(value)) {
return value.map((item) => cloneMessages(item)) as unknown as T;
}
if (value && typeof value === "object") {
const result: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
result[key] = cloneMessages(child);
}
return result as T;
}
return value;
}
/** เขียนค่าที่ dot path ที่ระบุ ถ้าปลายทางเป็น string เท่านั้น (ไม่ทับฟังก์ชัน) */
function setPath(
target: Record<string, unknown>,
path: string,
value: string,
): void {
const segments = path.split(".");
let cursor: Record<string, unknown> = target;
for (const segment of segments.slice(0, -1)) {
const next = cursor[segment];
if (!next || typeof next !== "object") return;
cursor = next as Record<string, unknown>;
}
const leaf = segments[segments.length - 1];
if (typeof cursor[leaf] !== "string") return;
cursor[leaf] = value;
}
/**
* รวมคำศัพท์ที่แก้จากหลังบ้านทับข้อความตั้งต้น
* คำศัพท์ที่ key ไม่ตรงหรือปลายทางไม่ใช่ข้อความจะถูกข้าม (ไม่ทำให้หน้าพัง)
*/
export function applyTerms(
base: Messages,
terms: TermEntry[],
locale: string,
): Messages {
const draft = cloneMessages(base) as unknown as Record<string, unknown>;
for (const term of terms) {
const value = term.values[locale];
if (typeof value !== "string" || value === "") continue;
setPath(draft, term.key, value);
}
return draft as unknown as Messages;
}
+32
View File
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { LOCALES, MESSAGES, translate } from "@/lib/i18n/messages";
import { CINEMA_CATEGORIES } from "@/lib/cinemas";
describe("i18n messages", () => {
it("มีข้อความครบทุก locale", () => {
for (const locale of LOCALES) {
const messages = MESSAGES[locale];
expect(messages.hero.titleSuffix.length).toBeGreaterThan(0);
expect(messages.list.title.length).toBeGreaterThan(0);
expect(messages.detail.otherCinemas.length).toBeGreaterThan(0);
}
});
it("แปลป้ายได้ครบทุกหมวดหมู่ที่ใช้กรอง", () => {
for (const locale of LOCALES) {
for (const category of CINEMA_CATEGORIES) {
expect(MESSAGES[locale].categories[category]).toBeTruthy();
}
}
});
it("ภาษาอังกฤษต่างจากไทยในข้อความหลัก", () => {
expect(MESSAGES.en.list.title).not.toBe(MESSAGES.th.list.title);
expect(MESSAGES.en.search.submit).not.toBe(MESSAGES.th.search.submit);
});
it("ค่าที่ไม่รู้จักถูกส่งกลับตามเดิม", () => {
expect(translate(MESSAGES.en.tags, "tag-ใหม่")).toBe("tag-ใหม่");
});
});
+403
View File
@@ -0,0 +1,403 @@
import type { CinemaCategory } from "@/lib/cinemas";
export type Locale = "th" | "en";
export const LOCALES: readonly Locale[] = ["th", "en"] as const;
export const DEFAULT_LOCALE: Locale = "th";
export const LOCALE_OPTIONS: ReadonlyArray<{
locale: Locale;
code: string;
name: string;
}> = [
{ locale: "th", code: "TH", name: "ไทย" },
{ locale: "en", code: "EN", name: "English" },
];
export type FacilityKey =
| "seating"
| "ticket"
| "restaurant"
| "cafe"
| "garden"
| "bookstore"
| "colearning"
| "other";
/** ลำดับคีย์สิ่งอำนวยความสะดวกที่ใช้แสดงผลและให้เลือกในหลังบ้าน */
export const FACILITY_KEYS: FacilityKey[] = [
"seating",
"ticket",
"restaurant",
"cafe",
"garden",
"bookstore",
"colearning",
"other",
];
export type TransportKey = "private_car" | "metro" | "bus";
export type Messages = {
meta: {
homeDescription: string;
cinemaNotFoundTitle: string;
};
hero: {
titlePrefix: string;
titleHighlight: string;
titleSuffix: string;
subtitle: string;
};
search: {
placeholder: string;
nearMe: string;
submit: string;
locating: string;
denied: string;
unsupported: string;
error: string;
sortedByDistance: string;
};
nav: {
home: string;
about: string;
};
about: {
title: string;
lead: string;
sections: Array<{ heading: string; body: string }>;
contactHeading: string;
contactNote: string;
};
list: {
title: string;
showMore: string;
empty: string;
};
card: {
seeDetail: string;
distanceFallback: string;
locationFallback: string;
categoryFallback: string;
};
detail: {
back: string;
openMap: string;
contactTitle: string;
paymentMethods: string;
showtimes: string;
facilities: string;
location: string;
otherCinemas: string;
contactsFallback: string;
paymentsFallback: string;
addressFallback: string;
/** ใช้เมื่อไม่มีทั้งแผนที่และพิกัด */
noData: string;
};
gallery: {
main: string;
second: string;
third: string;
previous: string;
next: string;
more: (remaining: number) => string;
};
notFound: {
title: string;
text: string;
cta: string;
};
/** ป้ายของหมวดหมู่ — คีย์ยังเป็นไทยเพื่อใช้กรองข้อมูล */
categories: Record<CinemaCategory, string>;
/** ป้ายของ tag ในข้อมูลโรงหนัง */
tags: Record<string, string>;
facilities: Record<FacilityKey, { title: string; sub: string }>;
transport: Record<TransportKey, string>;
/** ชื่อช่องทางชำระเงิน (คีย์คือค่าที่เก็บในข้อมูล) */
payments: Record<string, string>;
};
const TH: Messages = {
meta: {
homeDescription: "ค้นหาโรงภาพยนตร์อิสระ ทางเลือกในการดูหนัง",
cinemaNotFoundTitle: "ไม่พบโรงหนัง",
},
hero: {
titlePrefix: "ค้นพบ",
titleHighlight: "โรงหนังใหม่ๆ",
titleSuffix: "ใกล้คุณ",
subtitle:
"ค้นหาโรงภาพยนตร์ท้องถิ่น โรงภาพยนตร์อินดี้และกลุ่มคนฉายหนัง ทางเลือกในการดูหนัง",
},
search: {
placeholder: "ค้นหาชื่อโรงหนังหรือสถานที่ / จังหวัด / ประเภทหนัง",
nearMe: "ใกล้ฉัน",
submit: "ค้นหา",
locating: "กำลังหาตำแหน่ง…",
denied: "ไม่ได้รับอนุญาตให้ใช้ตำแหน่ง",
unsupported: "อุปกรณ์นี้ไม่รองรับการหาตำแหน่ง",
error: "หาตำแหน่งไม่สำเร็จ ลองอีกครั้ง",
sortedByDistance: "เรียงจากใกล้สุดไปไกลสุดแล้ว",
},
nav: {
home: "หน้าแรก",
about: "เกี่ยวกับเรา",
},
about: {
title: "เกี่ยวกับเรา",
lead: "AlterFlixHub รวมโรงหนังอิสระและอาร์ตเฮาส์ในประเทศไทยไว้ที่เดียว เพื่อให้คนรักหนังหาโรงที่ตรงใจและไปถึงได้ง่ายขึ้น",
sections: [
{
heading: "เราทำอะไร",
body: "รวมรายชื่อโรงหนังอิสระพร้อมรายละเอียดที่จำเป็น — ประเภทหนัง สิ่งอำนวยความสะดวก การเดินทาง และช่องทางติดต่อ พร้อมปุ่ม “ใกล้ฉัน” ที่เรียงโรงจากใกล้สุดไปไกลสุดด้วยระยะทางตามถนนจริง",
},
{
heading: "ข้อมูลมาจากไหน",
body: "ทีมงานกรอกและแก้ไขข้อมูลผ่านระบบหลังบ้าน พิกัดอ้างอิงจาก OpenStreetMap และคำนวณระยะทางด้วย OSRM หากข้อมูลใดคลาดเคลื่อน แจ้งเราได้ทุกช่องทาง",
},
{
heading: "ความเป็นส่วนตัว",
body: "เราไม่ใช้คุกกี้เพื่อการโฆษณา และไม่เก็บ IP หรือ User-Agent ของคุณ สถิติการค้นหาถูกเก็บแบบไม่ระบุตัวตนเพื่อปรับปรุงการค้นหาเท่านั้น",
},
{
heading: "หลายภาษา",
body: "เว็บรองรับภาษาไทยและอังกฤษ สลับได้ที่มุมขวาบนของทุกหน้า และจดจำภาษาที่คุณเลือกไว้ให้อัตโนมัติ",
},
],
contactHeading: "ติดต่อและแจ้งข้อมูล",
contactNote:
"พบข้อมูลโรงหนังผิด ต้องการเพิ่มโรงใหม่ หรืออยากให้เราช่วยประชาสัมพันธ์กิจกรรม ใช้ช่องทางโซเชียลในส่วนท้ายของหน้าเว็บได้เลย",
},
list: {
title: "รายชื่อโรงหนังทุกประเภทและกลุ่มคนฉายหนัง",
showMore: "แสดงเพิ่ม",
empty: "ไม่พบโรงหนังที่ตรงกับคำค้น ลองเปลี่ยนคำหรือหมวดหมู่ดู",
},
card: {
seeDetail: "ดูรายละเอียด",
distanceFallback: "— km.",
locationFallback: "ยังไม่ระบุสถานที่",
categoryFallback: "ยังไม่ระบุประเภท",
},
detail: {
back: "ย้อนกลับ",
openMap: "เปิด Google map",
contactTitle: "สอบถามข้อมูลและจองตั๋ว",
paymentMethods: "ช่องทางชำระเงิน",
showtimes: "ดูรอบฉาย",
facilities: "สิ่งอำนวยความสะดวก",
location: "ที่ตั้ง",
otherCinemas: "โรงหนังอิสระอื่นๆ",
contactsFallback: "ยังไม่ระบุช่องทางติดต่อ",
paymentsFallback: "ยังไม่ระบุ",
addressFallback: "ยังไม่ระบุที่อยู่",
noData: "ไม่มีข้อมูล",
},
gallery: {
main: "ภาพบรรยากาศโรงหนัง",
second: "ภาพที่ 2",
third: "ภาพที่ 3",
previous: "ก่อนหน้า",
next: "ถัดไป",
more: (remaining) => `${remaining}+`,
},
notFound: {
title: "ไม่พบโรงหนังที่ค้นหา",
text: "ลิงก์อาจเปลี่ยนแล้ว กลับไปเลือกจากรายชื่อโรงหนังอิสระได้เลย",
cta: "กลับหน้าแรก",
},
categories: {
ทั้งหมด: "ทั้งหมด",
ยอดนิยม: "ยอดนิยม",
อาร์ตเฮาส์: "อาร์ตเฮาส์",
สารคดี: "สารคดี",
หนังสั้น: "หนังสั้น",
หนังคลาสสิก: "หนังคลาสสิก",
หนังนานาชาติ: "หนังนานาชาติ",
หนังนอกกระแส: "หนังนอกกระแส",
หนังในกระแส: "หนังในกระแส",
หนังฝรั่งเศส: "หนังฝรั่งเศส",
กลุ่มคนฉายหนัง: "กลุ่มคนฉายหนัง",
หนังไทย: "หนังไทย",
},
tags: {
ยอดนิยม: "ยอดนิยม",
อาร์ตเฮาส์: "อาร์ตเฮาส์",
หนังคลาสสิก: "หนังคลาสสิก",
หนังนอกกระแส: "หนังนอกกระแส",
หนังในกระแส: "หนังในกระแส",
กลุ่มคนฉายหนัง: "กลุ่มคนฉายหนัง",
หนังไทย: "หนังไทย",
},
facilities: {
seating: { title: "โซนนั่งรอ", sub: "บริเวณโถงโรงภาพยนตร์" },
ticket: { title: "จุดจำหน่ายตั๋ว", sub: "Box Office ชั้น 5" },
restaurant: { title: "ร้านอาหาร", sub: "ภายในศูนย์การค้า" },
cafe: { title: "ร้านคาเฟ่", sub: "บริเวณโถงโรงภาพยนตร์" },
garden: { title: "สวนหย่อม", sub: "ลานกลางแจ้ง" },
bookstore: { title: "ร้านหนังสือ", sub: "ภายในศูนย์การค้า" },
colearning: { title: "Co-Learning Space", sub: "บริเวณโถงโรงภาพยนตร์" },
other: { title: "อื่นๆ", sub: "ร้านทำผม ร้านทำเล็บ" },
},
transport: {
private_car: "รถยนต์ส่วนตัว",
metro: "รถไฟฟ้า",
bus: "รถประจำทาง",
},
payments: {
เงินสด: "เงินสด",
บัตรเครดิต: "บัตรเครดิต",
สแกนจ่าย: "สแกนจ่าย",
},
};
const EN: Messages = {
meta: {
homeDescription: "Find independent cinemas — an alternative way to watch films",
cinemaNotFoundTitle: "Cinema not found",
},
hero: {
titlePrefix: "Discover ",
titleHighlight: "new cinemas",
titleSuffix: " near you",
subtitle:
"Find local cinemas, indie screens and film-screening collectives — an alternative way to watch films",
},
search: {
placeholder: "Search by cinema, place / province / film genre",
nearMe: "Near me",
submit: "Search",
locating: "Locating…",
denied: "Location permission denied",
unsupported: "This device cannot share its location",
error: "Could not get your location. Try again.",
sortedByDistance: "Sorted nearest first",
},
nav: {
home: "Home",
about: "About us",
},
about: {
title: "About us",
lead: "AlterFlixHub brings Thailand's independent and arthouse cinemas together in one place, so film lovers can find the right screen and get there easily.",
sections: [
{
heading: "What we do",
body: "We list independent cinemas with the details that matter — genres, facilities, how to get there and how to reach them — plus a “Near me” button that sorts every cinema by real road distance.",
},
{
heading: "Where the data comes from",
body: "Our team maintains the listings through the admin panel. Coordinates come from OpenStreetMap and distances are calculated with OSRM. If something looks wrong, tell us on any channel.",
},
{
heading: "Privacy",
body: "No advertising cookies, and we never store your IP address or user agent. Search statistics are recorded anonymously, only to improve search results.",
},
{
heading: "Two languages",
body: "The site works in Thai and English. Switch language at the top right of any page — your choice is remembered automatically.",
},
],
contactHeading: "Contact and corrections",
contactNote:
"Spotted wrong information, want to add a cinema, or need help promoting a screening? Use the social links in the footer of any page.",
},
list: {
title: "Local cinemas, indie screens and film collectives",
showMore: "Show more",
empty: "No cinema matches that search. Try another word or category.",
},
card: {
seeDetail: "View details",
distanceFallback: "— km.",
locationFallback: "Location not specified",
categoryFallback: "Genre not specified",
},
detail: {
back: "Back",
openMap: "Open Google map",
contactTitle: "Enquiries and tickets",
paymentMethods: "Payment methods",
showtimes: "See showtimes",
facilities: "Facilities",
location: "Location",
otherCinemas: "Other independent cinemas",
contactsFallback: "No contact channel yet",
paymentsFallback: "Not specified",
addressFallback: "Address not specified",
noData: "No data",
},
gallery: {
main: "Cinema photo",
second: "Photo 2",
third: "Photo 3",
previous: "Previous",
next: "Next",
more: (remaining) => `${remaining}+`,
},
notFound: {
title: "Cinema not found",
text: "The link may have changed. Pick a cinema from the list instead.",
cta: "Back to home",
},
categories: {
ทั้งหมด: "All",
ยอดนิยม: "Popular",
อาร์ตเฮาส์: "Arthouse",
สารคดี: "Documentary",
หนังสั้น: "Short films",
หนังคลาสสิก: "Classics",
หนังนานาชาติ: "International",
หนังนอกกระแส: "Independent",
หนังในกระแส: "Mainstream",
หนังฝรั่งเศส: "French films",
กลุ่มคนฉายหนัง: "Film collectives",
หนังไทย: "Thai films",
},
tags: {
ยอดนิยม: "Popular",
อาร์ตเฮาส์: "Arthouse",
หนังคลาสสิก: "Classics",
หนังนอกกระแส: "Independent",
หนังในกระแส: "Mainstream",
กลุ่มคนฉายหนัง: "Film collectives",
หนังไทย: "Thai films",
},
facilities: {
seating: { title: "Seating area", sub: "Cinema lobby" },
ticket: { title: "Ticket counter", sub: "Box office, 5th floor" },
restaurant: { title: "Restaurants", sub: "Inside the mall" },
cafe: { title: "Cafés", sub: "Cinema lobby" },
garden: { title: "Garden", sub: "Outdoor plaza" },
bookstore: { title: "Bookstore", sub: "Inside the mall" },
colearning: { title: "Co-learning space", sub: "Cinema lobby" },
other: { title: "Others", sub: "Hair and nail salons" },
},
transport: {
private_car: "Private car",
metro: "Metro",
bus: "Bus",
},
payments: {
เงินสด: "Cash",
บัตรเครดิต: "Credit card",
สแกนจ่าย: "QR payment",
},
};
export const MESSAGES: Record<Locale, Messages> = { th: TH, en: EN };
/** แปลค่าจาก dictionary — ค่าที่ไม่รู้จักถูกส่งกลับไปตามเดิมเพื่อไม่ให้ข้อความหาย */
export function translate(
dictionary: Record<string, string>,
key: string,
): string {
return dictionary[key] ?? key;
}
export function isLocale(value: string | undefined | null): value is Locale {
return value === "th" || value === "en";
}