feat: บทความ 2 หน้า + แชร์/ลิงก์ย่อ + PWA + แอนิเมชัน + SEO/AI + เอกสาร

- บทความจากหลังบ้าน: /for-film-lovers, /for-cinemas (ArticlePage + ArticleEditor แบบบล็อกย่อหน้า/รูป)
- แชร์: ปุ่มบนการ์ดและท้ายหน้ารายละเอียด · ลิงก์ย่อ /c/<slug> (302) · ธีมแก้วตาม DESIGN.md
- PWA: manifest/sw/offline + ถอดการล็อกซูม (WCAG 1.4.4) + touch target ≥44px
- แอนิเมชัน reveal: IntersectionObserver + gate ด้วย html.fx-motion · เคารพ prefers-reduced-motion
- ค้นหา: normalize/ตัดวรรณยุกต์ + AND หลายคำ + จัดอันดับ · รองรับ /?q= จาก SearchAction
- SEO: pageMeta (canonical/OG/Twitter) + JSON-LD (WebSite/Organization/BreadcrumbList/MovieTheater/Article)
- ไม่ฝังโดเมนในโค้ด: origin มาจาก request (x-forwarded-host/proto) ทั้ง canonical, sitemap, robots, ลิงก์แชร์
- กัน AI: robots.txt (Nitro route, บล็อก AI 21 ตัว) + ai.txt + OG image 1200x630
- เอกสาร: README สรุปโปรเจกต์, DESIGN.md (motion/PWA/SEO/ข้อมูล), architecture.html, admin-guide
- tests: 135 ผ่าน (16 ไฟล์)
This commit is contained in:
Bkk1234 committed 2026-11-10 02:31:10 +07:00
1 parent 1e84023a44
commit 319c271d23
72 files changed
+4731 -765

No files matched your search

+99
View File
@@ -0,0 +1,99 @@
import { describe, expect, it } from "vitest";
import {
countImages,
createImageBlock,
createParagraphBlock,
moveBlock,
removeBlock,
sanitizeArticleBlocks,
} from "./article";
describe("sanitizeArticleBlocks", () => {
it("ไม่ใช่ array → คืนอาร์เรย์ว่าง", () => {
expect(sanitizeArticleBlocks(undefined)).toEqual([]);
expect(sanitizeArticleBlocks("ข้อความ")).toEqual([]);
});
it("เก็บย่อหน้าที่มีข้อความ และตัดช่องว่างหัวท้าย", () => {
expect(
sanitizeArticleBlocks([{ type: "paragraph", text: " สวัสดี " }]),
).toEqual([{ type: "paragraph", text: "สวัสดี" }]);
});
it("ทิ้งย่อหน้าว่าง รูปที่ไม่มีลิงก์ และบล็อกชนิดที่ไม่รู้จัก", () => {
expect(
sanitizeArticleBlocks([
{ type: "paragraph", text: " " },
{ type: "image", src: " ", alt: "ไม่มีรูป" },
{ type: "video", src: "x.mp4" },
{ type: "paragraph", text: "เก็บอันนี้" },
]),
).toEqual([{ type: "paragraph", text: "เก็บอันนี้" }]);
});
it("รูปเก็บ src/alt/caption และตัดฟิลด์เกินทิ้ง", () => {
expect(
sanitizeArticleBlocks([
{
type: "image",
src: " /images/a.jpg ",
alt: " บรรยากาศ ",
caption: " โรงใหม่ ",
evil: "x",
},
]),
).toEqual([
{
type: "image",
src: "/images/a.jpg",
alt: "บรรยากาศ",
caption: "โรงใหม่",
},
]);
});
it("คงลำดับบล็อกตามที่รับมา", () => {
const blocks = sanitizeArticleBlocks([
{ type: "paragraph", text: "หนึ่ง" },
{ type: "image", src: "/a.jpg" },
{ type: "paragraph", text: "สอง" },
]);
expect(blocks.map((block) => block.type)).toEqual([
"paragraph",
"image",
"paragraph",
]);
});
});
describe("moveBlock / removeBlock", () => {
const blocks = [
createParagraphBlock("หนึ่ง"),
createParagraphBlock("สอง"),
createImageBlock(),
];
it("เลื่อนขึ้น/ลงสลับตำแหน่งถูกต้อง", () => {
expect(
moveBlock(blocks, 1, -1).map((b) =>
b.type === "paragraph" ? b.text : "img",
),
).toEqual(["สอง", "หนึ่ง", "img"]);
expect(moveBlock(blocks, 0, 1)[1]).toEqual(blocks[0]);
});
it("ไม่ทำอะไรเมื่อเกินขอบ", () => {
expect(moveBlock(blocks, 0, -1)).toEqual(blocks);
expect(moveBlock(blocks, blocks.length - 1, 1)).toEqual(blocks);
});
it("ลบบล็อกตามตำแหน่ง และไม่แตะเมื่อ index ผิด", () => {
expect(removeBlock(blocks, 1)).toHaveLength(2);
expect(removeBlock(blocks, 99)).toHaveLength(3);
});
it("นับจำนวนรูปได้", () => {
expect(countImages(blocks)).toBe(1);
});
});
+89
View File
@@ -0,0 +1,89 @@
/**
* ตัวช่วยจัดการบล็อกบทความของหน้า "สำหรับคนทำโรงหนัง"
* แยกออกมาเป็นฟังก์ชันบริสุทธิ์เพื่อเทสต์ได้โดยไม่ต้องพึ่ง fs หรือ React
*/
import type {
ArticleBlock,
ArticleImage,
ArticleParagraph,
} from "@/lib/content-types";
function asString(value: unknown): string {
return typeof value === "string" ? value : "";
}
/**
* ตรวจบล็อกที่รับมาจากหลังบ้าน/ไฟล์ JSON
* - เก็บเฉพาะชนิดที่รู้จัก (paragraph / image)
* - ย่อหน้าว่าง และรูปที่ไม่มี src → ทิ้ง
* - ฟิลด์เกินถูกตัดทิ้ง (ไม่ให้ข้อมูลแปลกปลอมไหลเข้า store)
*/
export function sanitizeArticleBlocks(input: unknown): ArticleBlock[] {
if (!Array.isArray(input)) return [];
const blocks: ArticleBlock[] = [];
for (const item of input) {
if (!item || typeof item !== "object") continue;
const raw = item as Record<string, unknown>;
const type = asString(raw.type);
if (type === "paragraph") {
const text = asString(raw.text).trim();
if (text) blocks.push({ type: "paragraph", text });
continue;
}
if (type === "image") {
const src = asString(raw.src).trim();
if (!src) continue;
const block: ArticleImage = {
type: "image",
src,
alt: asString(raw.alt).trim(),
caption: asString(raw.caption).trim(),
};
blocks.push(block);
}
}
return blocks;
}
/** ย่อหน้าใหม่ (ว่าง) สำหรับปุ่ม "เพิ่มย่อหน้า" */
export function createParagraphBlock(text = ""): ArticleParagraph {
return { type: "paragraph", text };
}
/** รูปใหม่ (ว่าง) สำหรับปุ่ม "เพิ่มรูป" */
export function createImageBlock(): ArticleImage {
return { type: "image", src: "", alt: "", caption: "" };
}
/** สลับตำแหน่งบล็อกขึ้น/ลง — คืนรายการใหม่ และไม่ทำอะไรถ้าเกินขอบ */
export function moveBlock(
blocks: ArticleBlock[],
index: number,
direction: -1 | 1,
): ArticleBlock[] {
const target = index + direction;
if (index < 0 || index >= blocks.length) return blocks;
if (target < 0 || target >= blocks.length) return blocks;
const next = [...blocks];
const [moved] = next.splice(index, 1);
next.splice(target, 0, moved);
return next;
}
/** ลบบล็อกตามตำแหน่ง */
export function removeBlock(
blocks: ArticleBlock[],
index: number,
): ArticleBlock[] {
if (index < 0 || index >= blocks.length) return blocks;
return blocks.filter((_, i) => i !== index);
}
/** จำนวนรูปในบทความ (ใช้แสดงสรุป/เตือนในหลังบ้าน) */
export function countImages(blocks: ArticleBlock[]): number {
return blocks.filter((block) => block.type === "image").length;
}
+1 -1
View File
@@ -3,10 +3,10 @@ import { describe, expect, it } from "vitest";
import type { Cinema } from "@/lib/cinemas";
import {
cinemaFacilities,
filterCinemas,
listOtherCinemas,
publiclyVisible,
} from "@/lib/cinemas";
import { filterCinemas } from "@/lib/search";
/**
* สเปกของกติกาที่เพิ่มเข้ามา: ซ่อนโรง (hidden) + สิ่งอำนวยความสะดวกต่อโรง
-33
View File
@@ -1,44 +1,11 @@
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();
+4 -29
View File
@@ -4,9 +4,9 @@
* ข้อความอังกฤษเป็นฟิลด์เสริม (*_en) ถ้าไม่กรอกจะ fallback เป็นไทย
*/
import type { Coordinates } from "@/lib/geo";
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 = {
/** ใช้เลือกไอคอนและชื่อวิธีเดินทางจากข้อความแปล */
@@ -332,9 +332,9 @@ export function cinemaFacilities(cinema: Cinema): FacilityKey[] {
}
/** หมวดที่เลือกได้ในหลังบ้าน — ตัด "ทั้งหมด" ออกเพราะใช้เป็นตัวกรอง "ไม่กรอง" */
export const ASSIGNABLE_CATEGORIES: CinemaCategory[] =
CINEMA_CATEGORIES.filter((category) => category !== DEFAULT_CATEGORY);
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);
@@ -352,31 +352,6 @@ 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,
+88
View File
@@ -0,0 +1,88 @@
import { describe, expect, it } from "vitest";
import { seedForCinemas, seedForFilmLovers } from "./content-seed";
import { sanitizeForCinemas, sanitizeForFilmLovers } from "./content.server";
/**
* ทดสอบตัวตรวจข้อมูลของหน้าบทความทั้งสองหน้า
* (สำหรับคนทำโรงหนัง / สำหรับคนรักหนัง)
* ค่าที่เว้นว่าง/ผิดรูปแบบต้องถูกแทนด้วยค่าเริ่มต้น ไม่ใช่ปล่อยให้หน้าเว็บว่าง
*/
describe("sanitizeForCinemas", () => {
const seed = seedForCinemas();
it("ไม่ส่งข้อมูลมา → คืนค่าเริ่มต้นทั้งสองภาษา", () => {
expect(sanitizeForCinemas(undefined)).toEqual(seed);
expect(sanitizeForCinemas("ผิดรูปแบบ")).toEqual(seed);
});
it("เก็บบล็อกที่ถูกต้องตามลำดับ และตัดบล็อกที่ว่าง", () => {
const result = sanitizeForCinemas({
th: {
title: "สำหรับคนทำโรงหนัง",
lead: "เกริ่น",
blocks: [
{ type: "paragraph", text: "หนึ่ง" },
{ type: "paragraph", text: " " },
{ type: "image", src: "/images/a.jpg", alt: "a", caption: "" },
{ type: "image", src: "" },
],
contactHeading: "ติดต่อ",
contactNote: "โน้ต",
},
});
expect(result.th.blocks).toEqual([
{ type: "paragraph", text: "หนึ่ง" },
{ type: "image", src: "/images/a.jpg", alt: "a", caption: "" },
]);
expect(result.th.title).toBe("สำหรับคนทำโรงหนัง");
});
it("ฟิลด์ที่เว้นว่างถูกแทนด้วยค่าเริ่มต้น", () => {
const result = sanitizeForCinemas({
th: {
title: " ",
lead: "",
blocks: [],
contactHeading: "",
contactNote: "",
},
});
expect(result.th.title).toBe(seed.th.title);
expect(result.th.lead).toBe(seed.th.lead);
expect(result.th.blocks).toEqual(seed.th.blocks);
expect(result.th.contactHeading).toBe(seed.th.contactHeading);
expect(result.th.contactNote).toBe(seed.th.contactNote);
});
it("ภาษา en ที่ไม่ส่งมาจะได้ค่าเริ่มต้นของ en", () => {
const result = sanitizeForCinemas({ th: { title: "ไทยเท่านั้น" } });
expect(result.en).toEqual(seed.en);
});
});
describe("sanitizeForFilmLovers", () => {
const seed = seedForFilmLovers();
it("ไม่ส่งข้อมูลมา → ค่าเริ่มต้นของหน้า 'สำหรับคนรักหนัง'", () => {
expect(sanitizeForFilmLovers(undefined)).toEqual(seed);
expect(seed.th.title).not.toBe(seedForCinemas().th.title);
});
it("เก็บบล็อกและหัวเรื่องที่ส่งมา ตัดบล็อกว่าง", () => {
const result = sanitizeForFilmLovers({
th: {
title: "สำหรับคนรักหนัง",
blocks: [
{ type: "paragraph", text: "ย่อหน้า" },
{ type: "image", src: "/images/a.jpg", alt: "alt", caption: "" },
{ type: "paragraph", text: "" },
],
},
});
expect(result.th.blocks).toHaveLength(2);
expect(result.th.title).toBe("สำหรับคนรักหนัง");
expect(result.th.lead).toBe(seed.th.lead);
});
});
+48 -4
View File
@@ -1,13 +1,14 @@
import { CINEMAS } from "@/lib/cinemas";
import type { Locale } from "@/lib/i18n/messages";
import { MESSAGES } from "@/lib/i18n/messages";
import type {
AboutContent,
ArticleContent,
ContentStore,
FooterItem,
LocaleEntry,
TermEntry,
} from "@/lib/content-types";
import type { Locale } from "@/lib/i18n/messages";
import { MESSAGES } from "@/lib/i18n/messages";
import type { Messages } from "@/lib/i18n/messages";
export const DEFAULT_LOCALES: LocaleEntry[] = [
@@ -25,7 +26,9 @@ function flatten(
return;
}
if (value && typeof value === "object") {
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
for (const [key, child] of Object.entries(
value as Record<string, unknown>,
)) {
flatten(child, prefix ? `${prefix}.${key}` : key, out);
}
}
@@ -43,7 +46,10 @@ export function seedTerms(): TermEntry[] {
return keys.map((key) => ({
key,
values: Object.fromEntries(
Object.entries(perLocale).map(([locale, flat]) => [locale, flat[key] ?? ""]),
Object.entries(perLocale).map(([locale, flat]) => [
locale,
flat[key] ?? "",
]),
),
}));
}
@@ -111,5 +117,43 @@ export function seedContent(): ContentStore {
footer: DEFAULT_FOOTER,
},
about: seedAbout(),
forCinemas: seedForCinemas(),
forFilmLovers: seedForFilmLovers(),
};
}
/** ค่าเริ่มต้นหน้า "สำหรับคนทำโรงหนัง" — ย่อหน้าตั้งต้นมาจาก messages (แก้ต่อได้ในหลังบ้าน) */
export function seedForCinemas(): Record<Locale, ArticleContent> {
return seedArticle(MESSAGES.th.forCinemas, MESSAGES.en.forCinemas);
}
/** ค่าเริ่มต้นหน้า "สำหรับคนรักหนัง" */
export function seedForFilmLovers(): Record<Locale, ArticleContent> {
return seedArticle(MESSAGES.th.forFilmLovers, MESSAGES.en.forFilmLovers);
}
type SeedArticle = {
title: string;
lead: string;
paragraphs: string[];
contactHeading: string;
contactNote: string;
};
/** แปลงข้อความ i18n ของหน้าบทความ → บล็อกเริ่มต้น (ใช้ทั้งหน้าโรงหนังและคนรักหนัง) */
function seedArticle(
th: SeedArticle,
en: SeedArticle,
): Record<Locale, ArticleContent> {
return { th: toArticleContent(th), en: toArticleContent(en) };
}
function toArticleContent(source: SeedArticle): ArticleContent {
return {
title: source.title,
lead: source.lead,
blocks: source.paragraphs.map((text) => ({ type: "paragraph", text })),
contactHeading: source.contactHeading,
contactNote: source.contactNote,
};
}
+29
View File
@@ -20,6 +20,31 @@ export type AboutContent = {
contactNote: string;
};
/** ย่อหน้าหนึ่งบล็อกของบทความ (หน้า "สำหรับคนทำโรงหนัง") */
export type ArticleParagraph = {
type: "paragraph";
text: string;
};
/** รูปหนึ่งบล็อกของบทความ — caption ไม่ใส่ได้ */
export type ArticleImage = {
type: "image";
src: string;
alt: string;
caption: string;
};
export type ArticleBlock = ArticleParagraph | ArticleImage;
/** เนื้อหาหน้า "สำหรับคนทำโรงหนัง" หนึ่งภาษา — บทความแบบบล็อก เพิ่มทีละย่อหน้า/รูปได้ */
export type ArticleContent = {
title: string;
lead: string;
blocks: ArticleBlock[];
contactHeading: string;
contactNote: string;
};
export type FooterItem = {
id: string;
/** ชื่อไอคอน Tabler เช่น IconBrandFacebook */
@@ -51,4 +76,8 @@ export type ContentStore = {
site: SiteContent;
/** เนื้อหาหน้า "เกี่ยวกับเรา" แยกตามภาษา — แก้ได้จากหลังบ้าน */
about: Record<Locale, AboutContent>;
/** เนื้อหาหน้า "สำหรับคนทำโรงหนัง" (บทความแบบบล็อก) แยกตามภาษา — แก้ได้จากหลังบ้าน */
forCinemas: Record<Locale, ArticleContent>;
/** เนื้อหาหน้า "สำหรับคนรักหนัง" (บทความแบบบล็อก) แยกตามภาษา — แก้ได้จากหลังบ้าน */
forFilmLovers: Record<Locale, ArticleContent>;
};
+72 -6
View File
@@ -1,9 +1,24 @@
/**
* อ่าน/เขียนเนื้อหาที่แก้ได้จากหลังบ้าน (`data/content/content.json`)
*
* หมายเหตุเรื่องแคช: `cache` ด้านล่างเก็บผล sanitize ไว้ต่อ process (คีย์ = ความยาวไฟล์)
* ดังนั้นถ้าแก้ "ข้อความตั้งต้น" ใน `messages.ts` ต้องรีสตาร์ต/ให้ dev server โหลดโมดูลใหม่
* ไฟล์นี้จึงจะคำนวณ seed ใหม่ — การแก้ผ่านหน้า admin ไม่ต้องรีสตาร์ต (ไฟล์เปลี่ยนเอง)
*/
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import path from "node:path";
import { seedAbout, seedContent } from "@/lib/content-seed";
import { sanitizeArticleBlocks } from "@/lib/article";
import type { Cinema } from "@/lib/cinemas";
import {
seedAbout,
seedContent,
seedForCinemas,
seedForFilmLovers,
} from "@/lib/content-seed";
import type {
AboutContent,
ArticleContent,
ContentStore,
FooterItem,
LocaleEntry,
@@ -12,7 +27,6 @@ import type {
} 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");
@@ -48,9 +62,7 @@ function sanitizeFacilities(value: unknown): Cinema["facilities"] {
}
/** ตรวจข้อความเฉพาะโรงของแต่ละหัวข้อ — เก็บเฉพาะคีย์/ฟิลด์ที่รู้จัก */
function sanitizeFacilityDetails(
value: unknown,
): Cinema["facility_details"] {
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"]> = {};
@@ -201,7 +213,10 @@ export function sanitizeAbout(input: unknown): Record<Locale, AboutContent> {
const body = asString(item.body).trim();
return heading || body ? { heading, body } : null;
})
.filter((section): section is { heading: string; body: string } => section !== null)
.filter(
(section): section is { heading: string; body: string } =>
section !== null,
)
: fallback.sections;
return {
@@ -220,6 +235,55 @@ export function sanitizeAbout(input: unknown): Record<Locale, AboutContent> {
};
}
/**
* ตรวจเนื้อหาหน้าบทความ (ใช้ทั้ง "สำหรับคนทำโรงหนัง" และ "สำหรับคนรักหนัง")
*
* ทำไมต้องมี seed: ถ้า editor ส่งค่าที่ใช้ไม่ได้มา (บล็อกว่างทั้งหมด, ไม่ได้ส่งภาษาใดภาษา
* มาบ้าง) หน้าเว็บจะกลายเป็นหน้าว่าง — จึงต้องเติมข้อความตั้งต้นของภาษานั้นให้เสมอ
* บล็อกที่ผิดรูปแบบ/ว่างจะถูกตัดทิ้งด้วย sanitizeArticleBlocks
*/
function sanitizeArticlePage(
input: unknown,
seed: Record<Locale, ArticleContent>,
): Record<Locale, ArticleContent> {
if (!input || typeof input !== "object") return seed;
const raw = input as Record<string, unknown>;
function one(value: unknown, fallback: ArticleContent): ArticleContent {
if (!value || typeof value !== "object") return fallback;
const entry = value as Record<string, unknown>;
const blocks = sanitizeArticleBlocks(entry.blocks);
return {
title: asString(entry.title, "").trim() || fallback.title,
lead: asString(entry.lead).trim() || fallback.lead,
blocks: blocks.length > 0 ? blocks : fallback.blocks,
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 function sanitizeForCinemas(
input: unknown,
): Record<Locale, ArticleContent> {
return sanitizeArticlePage(input, seedForCinemas());
}
/** เนื้อหาหน้า "สำหรับคนรักหนัง" */
export function sanitizeForFilmLovers(
input: unknown,
): Record<Locale, ArticleContent> {
return sanitizeArticlePage(input, seedForFilmLovers());
}
/** อ่านเนื้อหาทั้งหมด — สร้างไฟล์เริ่มต้นให้อัตโนมัติเมื่อยังไม่มี */
export async function readContent(): Promise<ContentStore> {
let raw: string;
@@ -251,6 +315,8 @@ function sanitizeStore(input: unknown): ContentStore {
cinemas: sanitizeCinemas(raw.cinemas ?? []),
site: sanitizeSite(raw.site ?? {}),
about: sanitizeAbout(raw.about ?? {}),
forCinemas: sanitizeForCinemas(raw.forCinemas ?? {}),
forFilmLovers: sanitizeForFilmLovers(raw.forFilmLovers ?? {}),
};
}
+25 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
import { GALLERY_SLOTS, splitGallery } from "./gallery";
import { GALLERY_SLOTS, rotateGallery, splitGallery } from "./gallery";
const photosOf = (count: number) =>
Array.from({ length: count }, (_, index) => `/images/p${index + 1}.jpg`);
@@ -36,3 +36,27 @@ describe("splitGallery", () => {
}
});
});
describe("rotateGallery", () => {
it("ไม่มีรูป → อาร์เรย์ว่าง", () => {
expect(rotateGallery([], 3)).toEqual([]);
});
it("index 0 คงลำดับเดิม", () => {
expect(rotateGallery(photosOf(3), 0)).toEqual(photosOf(3));
});
it("index 1 เริ่มที่ภาพที่ 2 และวนภาพแรกไปท้าย", () => {
expect(rotateGallery(photosOf(4), 1)).toEqual([
"/images/p2.jpg",
"/images/p3.jpg",
"/images/p4.jpg",
"/images/p1.jpg",
]);
});
it("index ติดลบและเกินจำนวนวนกลับถูกต้อง", () => {
expect(rotateGallery(photosOf(3), -1)[0]).toBe("/images/p3.jpg");
expect(rotateGallery(photosOf(3), 4)[0]).toBe("/images/p2.jpg");
});
});
+11
View File
@@ -10,6 +10,17 @@ export type GalleryView = {
remaining: number;
};
/**
* หมุนรายการรูปให้เริ่มที่ index (ค่าติดลบ/เกินจำนวนได้ — วนกลับอัตโนมัติ)
* ใช้กับปุ่มก่อนหน้า/ถัดไปของแกลเลอรี: ภาพหลักเลื่อน และภาพย่อยเลื่อนตาม
*/
export function rotateGallery(photos: string[], index: number): string[] {
const total = photos.length;
if (total === 0) return [];
const start = ((index % total) + total) % total;
return [...photos.slice(start), ...photos.slice(0, start)];
}
/**
* แบ่งรูปทั้งหมดเป็นภาพหลัก + ภาพย่อย และนับรูปที่เหลือ
* ป้าย "+N" จึงมาจากจำนวนรูปจริง ไม่ใช่ค่าคงที่ในโค้ด
+95 -1
View File
@@ -39,6 +39,18 @@ export const FACILITY_KEYS: FacilityKey[] = [
export type TransportKey = "private_car" | "metro" | "bus";
/**
* ข้อความของหน้า "บทความ" ที่ใช้ร่วมกันสองหน้า
* (สำหรับคนทำโรงหนัง / สำหรับคนรักหนัง) — แก้โครงครั้งเดียวมีผลทั้งคู่
*/
export type ArticleMessages = {
title: string;
lead: string;
paragraphs: string[];
contactHeading: string;
contactNote: string;
};
export type Messages = {
meta: {
homeDescription: string;
@@ -63,6 +75,10 @@ export type Messages = {
nav: {
home: string;
about: string;
forCinemas: string;
forFilmLovers: string;
menu: string;
language: string;
};
about: {
title: string;
@@ -71,6 +87,15 @@ export type Messages = {
contactHeading: string;
contactNote: string;
};
forCinemas: ArticleMessages;
forFilmLovers: ArticleMessages;
/** ข้อความปุ่ม/สถานะการแชร์ */
share: {
label: string;
pageLabel: string;
copied: string;
failed: string;
};
list: {
title: string;
showMore: string;
@@ -145,6 +170,10 @@ const TH: Messages = {
nav: {
home: "หน้าแรก",
about: "เกี่ยวกับเรา",
forCinemas: "สำหรับคนทำโรงหนัง",
forFilmLovers: "สำหรับคนรักหนัง",
menu: "เมนู",
language: "ภาษา",
},
about: {
title: "เกี่ยวกับเรา",
@@ -171,6 +200,36 @@ const TH: Messages = {
contactNote:
"พบข้อมูลโรงหนังผิด ต้องการเพิ่มโรงใหม่ หรืออยากให้เราช่วยประชาสัมพันธ์กิจกรรม ใช้ช่องทางโซเชียลในส่วนท้ายของหน้าเว็บได้เลย",
},
forCinemas: {
title: "สำหรับคนทำโรงหนัง",
lead: "AlterFlixHub เปิดพื้นที่ให้โรงหนังอิสระ กลุ่มคนฉายหนัง และโรงหนังท้องถิ่นได้เล่าเรื่องของตัวเอง พร้อมรายละเอียดที่คนดูอยากรู้ก่อนออกจากบ้าน",
paragraphs: [
"โรงหนังเล็ก ๆ ในประเทศไทยมีเรื่องเล่าที่น่าสนใจไม่แพ้โรงใหญ่ แต่หลายโรงยังไม่มีพื้นที่สื่อสารกับคนดูอย่างเป็นระบบ ข้อมูลกระจัดกระจาย และคนดูก็หาไม่เจอ",
"เราจึงเปิดพื้นที่ให้ทุกโรงสร้างหน้ารายละเอียดของตัวเองบน AlterFlixHub ระบุที่ตั้ง วิธีเดินทาง สิ่งอำนวยความสะดวก พร้อมภาพบรรยากาศจริง เพื่อให้คนดูตัดสินใจได้ก่อนเดินทาง",
"ถ้าคุณดูแลโรงหนัง กลุ่มคนฉายหนัง หรือพื้นที่ฉายหนังชุมชน แล้วอยากมีหน้ารายละเอียดบน AlterFlixHub ส่งข้อมูลมาให้ทีมงานได้เลย เราช่วยตรวจข้อมูลและจัดหน้าให้ในช่วงเริ่มต้น",
],
contactHeading: "สนใจลงโรงหนังกับเรา",
contactNote:
"ส่งชื่อโรง ที่ตั้ง และภาพบรรยากาศมาให้ทีมงานผ่านช่องทางโซเชียลในส่วนท้ายของหน้าเว็บ เราจะติดต่อกลับภายใน 2 วันทำการ",
},
forFilmLovers: {
title: "สำหรับคนรักหนัง",
lead: "รวมทางเลือกสำหรับคนที่อยากดูหนังมากกว่าหนังกระแสหลัก — โรงอาร์ตเฮาส์ กลุ่มคนฉายหนัง และรอบฉายพิเศษที่คัดมาแล้ว",
paragraphs: [
"ถ้าคุณตามหาหนังที่ไม่ได้อยู่ในโรงใหญ่ AlterFlixHub ช่วยให้เจอโรงที่ฉายหนังนอกกระแส สารคดี หนังคลาสสิก และรอบฉายพิเศษได้ในไม่กี่คลิก",
"ทุกโรงในเว็บมีข้อมูลที่คนดูอยากรู้ก่อนตัดสินใจ — ประเภทหนังที่ฉาย สิ่งอำนวยความสะดวก วิธีเดินทาง และภาพบรรยากาศจริง พร้อมปุ่ม “ใกล้ฉัน” ที่เรียงโรงจากใกล้สุดไปไกลสุดตามระยะทางถนนจริง",
"อยากแนะนำโรงใหม่ กลุ่มฉายหนัง หรือกิจกรรมที่ควรอยู่ในหน้านี้ ส่งมาให้ทีมงานได้เลย เราตรวจข้อมูลและเพิ่มให้ทุกสัปดาห์",
],
contactHeading: "มีโรงหรือรอบฉายที่อยากแนะนำ",
contactNote:
"ส่งชื่อโรงหรือกิจกรรมพร้อมลิงก์มาให้ทีมงานผ่านช่องทางโซเชียลในส่วนท้ายของหน้าเว็บ เราจะตรวจและเพิ่มให้ทุกสัปดาห์",
},
share: {
label: "แชร์",
pageLabel: "แชร์หน้านี้",
copied: "คัดลอกลิงก์แล้ว",
failed: "แชร์ไม่สำเร็จ",
},
list: {
title: "รายชื่อโรงหนังทุกประเภทและกลุ่มคนฉายหนัง",
showMore: "แสดงเพิ่ม",
@@ -256,7 +315,8 @@ const TH: Messages = {
const EN: Messages = {
meta: {
homeDescription: "Find independent cinemas — an alternative way to watch films",
homeDescription:
"Find independent cinemas — an alternative way to watch films",
cinemaNotFoundTitle: "Cinema not found",
},
hero: {
@@ -279,6 +339,10 @@ const EN: Messages = {
nav: {
home: "Home",
about: "About us",
forCinemas: "For cinemas",
forFilmLovers: "For film lovers",
menu: "Menu",
language: "Language",
},
about: {
title: "About us",
@@ -305,6 +369,36 @@ const EN: Messages = {
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.",
},
forCinemas: {
title: "For cinemas",
lead: "AlterFlixHub gives independent cinemas, screening collectives and local theatres a place to tell their own story — with the details filmgoers need before leaving home.",
paragraphs: [
"Small cinemas in Thailand have stories as compelling as the big chains, yet many still have no structured way to reach their audience: information is scattered and viewers cannot find them.",
"This page opens a dedicated detail page for any cinema on AlterFlixHub — location, how to get there, facilities and real photos — so people can decide before they travel.",
"If you run a cinema, a screening collective or a community screening space and want to be listed, send your information to our team. We verify the details and set the page up for you during the launch period.",
],
contactHeading: "Want your cinema listed?",
contactNote:
"Send your cinema name, address and a few photos through the social links in the footer — we reply within two business days.",
},
forFilmLovers: {
title: "For film lovers",
lead: "A curated path for anyone who wants more than the mainstream — arthouse screens, screening collectives and special programmes, all in one place.",
paragraphs: [
"If you are looking for films that never reach the multiplex, AlterFlixHub helps you find the cinemas showing independent titles, documentaries, classics and special programmes in a few clicks.",
"Every cinema listed comes with the details that matter before you leave home — genres, facilities, how to get there and real photos — plus a “Near me” button that sorts everything by real road distance.",
"Know a cinema, a screening collective or an event that belongs here? Send it to our team and we will review it — new listings are added every week.",
],
contactHeading: "Know a cinema or a screening we should add?",
contactNote:
"Send the name and a link through the social channels in the footer — we review new listings every week.",
},
share: {
label: "Share",
pageLabel: "Share this page",
copied: "Link copied",
failed: "Couldn't share",
},
list: {
title: "Local cinemas, indie screens and film collectives",
showMore: "Show more",
+29
View File
@@ -0,0 +1,29 @@
/**
* ค่าคงที่ของ motion (ใช้ร่วมทุกหน้า)
*
* สคริปต์นี้ถูกฝังใน <head> (root.tsx) และรันก่อน paint เพื่อใส่คลาส `fx-motion`
* ให้ <html> เฉพาะเมื่อผู้ใช้ไม่ได้ขอ reduced motion → เนื้อหาไม่กระพริบตอนโหลด
* และถ้าปิด JS ไว้ก็ไม่มีคลาสนี้ = ไม่มีอะไรถูกซ่อน (progressive enhancement)
*/
export const MOTION_INIT_SCRIPT = `(function(){try{var m=window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)");if(m&&m.matches){return}document.documentElement.classList.add("fx-motion")}catch(e){}})();`;
/** รูปแบบการโผล่ของบล็อก — ตรงกับ selector `[data-reveal="…"]` ใน global.css */
export type RevealKind = "rise" | "fade" | "zoom";
/**
* เลื่อนหน้าไปที่ element โดยเคารพการตั้งค่า "ลดการเคลื่อนไหว" ของผู้ใช้
* (ผู้ที่ปิดอนิเมชันจะกระโดดไปทันที ไม่มีการเลื่อนแบบ smooth)
*/
export function scrollIntoViewRespectMotion(
element: HTMLElement | null,
block: ScrollLogicalPosition = "start",
): void {
if (!element) return;
const reduceMotion =
typeof window !== "undefined" &&
window.matchMedia("(prefers-reduced-motion: reduce)").matches;
element.scrollIntoView({
behavior: reduceMotion ? "auto" : "smooth",
block,
});
}
+14
View File
@@ -0,0 +1,14 @@
/**
* origin ของหน้าปัจจุบัน สำหรับใช้ใน `meta()` ของ route
*
* ทำไมต้องมาใน loader: `meta()` ไม่มี access ต่อ request และ (ใน framework นี้)
* ไม่ได้รับ loader data ของ root ผ่าน `matches` — route ที่มี meta จึงต้อง
* ส่ง origin ของคำขอตัวเองกลับมาใน loader แล้วอ่านจาก `loaderData.origin`
*/
import { originFromRequest } from "@/lib/request-origin";
import { configuredOrigin } from "@/lib/site";
/** โดเมนของ request นี้ — ตั้ง env SITE_URL เฉพาะกรณีต้องบังคับ */
export function resolvePageOrigin(request: Request): string {
return configuredOrigin() || originFromRequest(request);
}
+44
View File
@@ -0,0 +1,44 @@
/**
* ลงทะเบียน service worker (PWA)
*
* - ลงทะเบียนทุกสภาพแวดล้อม: จำเป็นเพื่อ "ยึดอำนาจ" จาก SW เวอร์ชันเก่าที่อาจค้างอยู่
* (SW ตัวใหม่จะลบแคชเก่าทิ้งในขั้น activate)
* - ในโหมด dev ตัว SW จะไม่แตะโมดูลของ Vite (`/app/*`, `/node_modules/*`, `/@vite/*`)
* เพราะกฎใน public/sw.js แคชเฉพาะ `/assets/*` กับไฟล์ static เท่านั้น → HMR ทำงานปกติ
* - ถ้ามี SW ตัวใหม่รออยู่ ให้สั่ง skipWaiting ทันที (ไม่ต้องรอปิดแท็บทั้งหมด)
* ไม่ reload หน้าอัตโนมัติเพื่อเลี่ยงลูปตอน dev
*/
export function registerServiceWorker(): void {
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) return;
const start = () => {
navigator.serviceWorker
.register("/sw.js", { scope: "/", updateViaCache: "none" })
.then((registration) => {
// ตรวจไฟล์ sw.js ใหม่จากเครือข่ายทุกครั้ง (ไม่ใช้ HTTP cache)
registration.update().catch(() => undefined);
const promote = (worker: ServiceWorker | null) => {
if (!worker) return;
worker.addEventListener("statechange", () => {
if (worker.state === "installed" && navigator.serviceWorker.controller) {
worker.postMessage("SKIP_WAITING");
}
});
};
registration.addEventListener("updatefound", () => {
promote(registration.installing);
});
// มีตัวใหม่รออยู่แล้ว (เช่น เปิดแท็บค้างไว้ตอนปล่อยเวอร์ชัน)
if (registration.waiting) registration.waiting.postMessage("SKIP_WAITING");
})
.catch(() => {
// ลงทะเบียนไม่ได้ (เบราว์เซอร์เก่า/โหมดส่วนตัว) — เว็บยังใช้งานปกติ
});
};
if (document.readyState === "complete") start();
else window.addEventListener("load", start, { once: true });
}
+102
View File
@@ -0,0 +1,102 @@
/**
* ทดสอบการหา origin จาก request — หัวใจของ "ไม่ฝังโดเมนในโค้ด"
* (canonical/OG/sitemap/robots ใช้ค่านี้ทั้งหมด)
*/
import { describe, expect, it } from "vitest";
import {
normalizeOrigin,
originFromHeaders,
originFromRequest,
} from "@/lib/request-origin";
function headers(map: Record<string, string>): Headers {
return new Headers(map);
}
describe("normalizeOrigin", () => {
it("ตัด / ท้ายและช่องว่าง", () => {
expect(normalizeOrigin(" https://a.test/ ")).toBe("https://a.test");
});
it("เติม https ให้ถ้าไม่มี scheme", () => {
expect(normalizeOrigin("a.test")).toBe("https://a.test");
});
it("ค่าว่าง → ค่าว่าง", () => {
expect(normalizeOrigin(" ")).toBe("");
});
});
describe("originFromHeaders", () => {
it("ใช้ host + https เป็นค่าเริ่มต้น", () => {
expect(
originFromHeaders(headers({ host: "alterflixhub.hobbypj.com" })),
).toBe("https://alterflixhub.hobbypj.com");
});
it("เชื่อ x-forwarded-host / x-forwarded-proto (อยู่หลัง proxy)", () => {
expect(
originFromHeaders(
headers({
host: "internal:3000",
"x-forwarded-host": "alterflixhub.hobbypj.com",
"x-forwarded-proto": "https",
}),
),
).toBe("https://alterflixhub.hobbypj.com");
});
it("รับค่าแรกเมื่อ header มีหลายชั้น", () => {
expect(
originFromHeaders(
headers({
"x-forwarded-host": "a.test, b.test",
"x-forwarded-proto": "http, https",
}),
),
).toBe("http://a.test");
});
it("คง port ไว้ (localhost dev)", () => {
expect(
originFromHeaders(
headers({ host: "localhost:8080", "x-forwarded-proto": "http" }),
),
).toBe("http://localhost:8080");
});
it("ไม่มี host → ค่าว่าง", () => {
expect(originFromHeaders(headers({}))).toBe("");
});
it("รองรับ plain object ของ h3", () => {
expect(
originFromHeaders({ host: "h3.test", "x-forwarded-proto": "https" }),
).toBe("https://h3.test");
});
});
describe("originFromRequest", () => {
it("อ่าน host จาก header และใช้โปรโตคอลจริงของ request (dev = http)", () => {
const request = new Request("http://internal/", {
headers: { host: "alterflixhub.hobbypj.com" },
});
expect(originFromRequest(request)).toBe("http://alterflixhub.hobbypj.com");
});
it("เชื่อ x-forwarded-proto เมื่ออยู่หลัง proxy ที่ปิด TLS", () => {
const request = new Request("http://internal/", {
headers: {
host: "alterflixhub.hobbypj.com",
"x-forwarded-proto": "https",
},
});
expect(originFromRequest(request)).toBe("https://alterflixhub.hobbypj.com");
});
it("ไม่มี header host → ใช้ URL ของ request", () => {
const request = new Request("http://localhost:8080/cinema/x");
expect(originFromRequest(request)).toBe("http://localhost:8080");
});
});
+71
View File
@@ -0,0 +1,71 @@
/**
* หา "origin" ของคำขอนี้ (เช่น `https://alterflixhub.hobbypj.com`, `http://localhost:8080`)
*
* ใช้แทนการฮาร์ดโค้ดโดเมน: canonical / OG / sitemap / robots มาจาก request จริงทุกครั้ง
* รองรับหลัง reverse proxy (Cloudflare, Nginx, Vercel) ที่ส่ง `x-forwarded-host` / `x-forwarded-proto`
*/
/** header ที่อ่านได้ — รองรับทั้ง `Headers`, plain object ของ h3 และค่า undefined */
export type HeaderSource =
| { get(name: string): string | null }
| Record<string, string | string[] | undefined>;
/** ตัด `/` ท้าย, เติม scheme ให้ถ้าไม่มี, คืน "" ถ้าว่าง */
export function normalizeOrigin(value: string): string {
const trimmed = value.trim().replace(/\/+$/, "");
if (trimmed === "") return "";
return /^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed)
? trimmed
: `https://${trimmed}`;
}
function readHeader(source: HeaderSource, name: string): string {
if (typeof (source as { get?: unknown }).get === "function") {
const value = (source as { get(n: string): string | null }).get(name);
return typeof value === "string" ? value : "";
}
const record = source as Record<string, string | string[] | undefined>;
const value = record[name.toLowerCase()] ?? record[name];
if (Array.isArray(value)) return value[0] ?? "";
return typeof value === "string" ? value : "";
}
/** ค่าแรกก่อนจุลภาค (`a, b` → `a`) — proxy บางตัวต่อ host หลายชั้น */
function firstValue(value: string): string {
return value.split(",")[0]?.trim() ?? "";
}
export function originFromHeaders(
source: HeaderSource,
fallbackProto = "https",
): string {
const forwardedHost = firstValue(readHeader(source, "x-forwarded-host"));
const host =
forwardedHost !== ""
? forwardedHost
: firstValue(readHeader(source, "host"));
if (host === "") return "";
// proxy ที่ไม่ส่ง x-forwarded-proto → ใช้โปรโตคอลจริงของคำขอ (dev = http)
const forwardedProto = firstValue(readHeader(source, "x-forwarded-proto"));
const proto = forwardedProto !== "" ? forwardedProto : fallbackProto;
return normalizeOrigin(`${proto}://${host}`);
}
/** origin ของ Request (ใช้ใน loader / resource route) */
export function originFromRequest(request: Request): string {
let protocol = "https";
try {
protocol = new URL(request.url).protocol.replace(":", "");
} catch {
// URL เพี้ยน → ใช้ค่าเริ่มต้น
}
const fromHeaders = originFromHeaders(request.headers, protocol);
if (fromHeaders !== "") return fromHeaders;
// ไม่มี header host (เช่นเรียกภายใน) → ใช้ URL ที่ framework สร้างให้
try {
return normalizeOrigin(new URL(request.url).origin);
} catch {
return "";
}
}
+183
View File
@@ -0,0 +1,183 @@
import { describe, expect, it } from "vitest";
import { CINEMAS, DEFAULT_CATEGORY, type Cinema } from "./cinemas";
import {
buildSearchIndex,
FIELD_WEIGHTS,
filterCinemas,
foldSearchText,
normalizeSearchText,
scoreCinema,
searchTokens,
} from "./search";
describe("normalizeSearchText", () => {
it("ตัดช่องว่างหัวท้าย ลดตัวพิมพ์ และแปลงตัวคั่นเป็นช่องว่าง", () => {
expect(normalizeSearchText(" HOUSE · สามย่าน ")).toBe("house สามย่าน");
expect(normalizeSearchText("DOC CLUB & FRIENDS")).toBe("doc club friends");
});
it("ตัดอักขระล่องหนที่ติดมากับการคัดลอก", () => {
expect(normalizeSearchText("เฮ้า\u200Bส์")).toBe("เฮ้าส์");
});
});
describe("foldSearchText", () => {
it("ตัดวรรณยุกต์ภาษาอังกฤษ (Française → francaise)", () => {
expect(foldSearchText("Française")).toBe("francaise");
});
it("ตัดวรรณยุกต์ไทย (เฮ้าส์ → เฮาส)", () => {
expect(foldSearchText("เฮ้าส์")).toBe("เฮาส");
});
});
describe("searchTokens", () => {
it("แยกหลายคำ และคืนอาร์เรย์ว่างเมื่อไม่มีคำค้น", () => {
expect(searchTokens(" สามย่าน house ")).toEqual(["สามย่าน", "house"]);
expect(searchTokens(" ")).toEqual([]);
expect(searchTokens("·")).toEqual([]);
});
});
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([]);
});
// ── ค้นด้วยข้อความที่แสดงบนการ์ดจริง ────────────────────────────────
it("ค้นด้วยชื่อไทยที่แสดงบนการ์ด (name_th) ได้", () => {
const result = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "เซ็นจูรี่มูฟวี่พลาซ่า",
});
expect(result.map((cinema) => cinema.slug)).toContain(
"century-the-movie-plaza",
);
});
it("ค้นด้วยชื่อไทยที่พิมพ์ไม่ครบ (คำนำหน้า) ได้", () => {
const result = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "เซ็นจูรี่",
});
expect(result.length).toBeGreaterThan(1);
expect(
result.every((cinema) => (cinema.name_th ?? "").includes("เซ็นจูรี่")),
).toBe(true);
});
it("ค้นชื่ออังกฤษแบบไม่ใส่วรรณยุกต์ก็เจอ", () => {
expect(
filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "francaise",
}).map((cinema) => cinema.slug),
).toContain("alliance-francaise-de-bangkok");
});
it("ค้นด้วยชื่อหมวดที่แสดงบนการ์ดได้ (ทั้งคีย์ไทยและป้ายภาษาอังกฤษ)", () => {
const th = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "อาร์ตเฮาส์",
});
expect(th.map((cinema) => cinema.slug)).toContain("house-cinema-samyan");
const en = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "arthouse",
tagLabels: { อาร์ตเฮาส์: "Arthouse" },
});
expect(en.map((cinema) => cinema.slug)).toContain("house-cinema-samyan");
});
it("ค้นหลายคำสลับลำดับได้ (ทุกคำต้องเจอ)", () => {
const result = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "samyan HOUSE",
});
expect(result.map((cinema) => cinema.slug)).toEqual([
"house-cinema-samyan",
]);
});
it("ค้นข้อความที่คัดลอกมาจากการ์ดทั้งบรรทัด (มีตัวคั่น ·) ได้", () => {
const result = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "HOUSE สามย่าน · อาร์ตเฮาส์",
});
expect(result.map((cinema) => cinema.slug)).toContain(
"house-cinema-samyan",
);
});
it("เรียงผลลัพธ์ที่ตรงที่สุดก่อน", () => {
const result = filterCinemas(CINEMAS, {
category: DEFAULT_CATEGORY,
query: "cineplex",
});
expect(result[0]?.slug).toBe("thana-cineplex");
});
});
describe("scoreCinema", () => {
const house = CINEMAS.find(
(cinema) => cinema.slug === "house-cinema-samyan",
) as Cinema;
it("คืน 0 เมื่อไม่มีคำค้น หรือคำค้นไม่ตรงเลย", () => {
expect(scoreCinema(house, [])).toBe(0);
expect(scoreCinema(house, searchTokens("zzzz"))).toBe(0);
});
it("ชื่อที่ตรงทั้งคำได้คะแนนสูงกว่าการเจอในรายละเอียด", () => {
const byName = scoreCinema(house, searchTokens("house"));
const byTag = scoreCinema(house, searchTokens("อาร์ตเฮาส์"));
expect(byName).toBeGreaterThan(byTag);
expect(byName).toBeGreaterThanOrEqual(FIELD_WEIGHTS.names);
});
});
describe("buildSearchIndex", () => {
it("เตรียมฟิลด์ชื่อ/สถานที่/หมวดไว้เทียบ และไม่เก็บค่าว่าง", () => {
const index = buildSearchIndex(CINEMAS[0], { อาร์ตเฮาส์: "Arthouse" });
expect(index.length).toBeGreaterThan(0);
expect(index.every((field) => field.exact !== "")).toBe(true);
expect(index.some((field) => field.exact.includes("arthouse"))).toBe(true);
expect(index.some((field) => field.group === "names")).toBe(true);
});
});
+211
View File
@@ -0,0 +1,211 @@
/**
* เครื่องยนต์ค้นหาโรงหนัง
*
* แยกออกจาก `app/lib/cinemas.ts` (ซึ่งเป็น "ข้อมูล + ตัวกรองหมวด") เพื่อให้แต่ละไฟล์
* ทำหน้าที่เดียว อ่านเข้าใจง่าย และเทสต์แยกได้โดยไม่ต้องโหลดข้อมูลทั้งชุด
*
* ลำดับการทำงาน
* 1) normalizeSearchText / foldSearchText — ทำให้ข้อความเทียบกันได้
* 2) searchTokens — แยกคำค้นเป็นหลายคำ (ทุกคำต้องเจอ = AND, เรียงสลับได้)
* 3) buildSearchIndex — เตรียมข้อความทุกฟิลด์ของโรงหนึ่ง (ทำครั้งเดียวต่อโรง)
* 4) matchLevel + FIELD_WEIGHTS — ให้คะแนนความตรง
* 5) scoreCinema / filterCinemas — รวมผลและเรียงจากตรงที่สุด
*/
import { hasCategory, type Cinema, type CinemaCategory } from "@/lib/cinemas";
/** อักขระล่องหนที่ติดมากับการคัดลอกข้อความ (zero-width, BOM) */
const ZERO_WIDTH = /[\u200B-\u200D\u2060\uFEFF]/g;
/** วรรณยุกต์/สระบน-ล่าง (combining marks) — ใช้เทียบแบบหลวม */
const COMBINING_MARKS = /\p{M}+/gu;
/**
* ปรับข้อความให้เทียบกันได้: NFKC, ตัดอักขระล่องหน, ตัวพิมพ์เล็ก,
* แปลงตัวคั่น (· • / & — …) เป็นช่องว่าง แล้วยุบช่องว่างซ้ำ
*/
export function normalizeSearchText(value: string): string {
return value
.normalize("NFKC")
.replace(ZERO_WIDTH, "")
.toLowerCase()
.replace(/[·•・,،.\\/_|+&()\[\]{}<>"'’‘`“”«»—–~*:;!?$%^@#№-]+/g, " ")
.replace(/\s+/g, " ")
.trim();
}
/**
* รูปแบบ "หลวม" ของข้อความ: ตัดวรรณยุกต์/สระบน-ล่างออก
* ทำให้ "Française" = "francaise", "เฮ้าส์" = "เฮาส" (พิมพ์ไม่ครบ/ไม่ใส่วรรณยุกต์ก็เจอ)
*/
export function foldSearchText(value: string): string {
return normalizeSearchText(value)
.normalize("NFD")
.replace(COMBINING_MARKS, "")
.replace(/[^\p{L}\p{N}\s]+/gu, " ")
.replace(/\s+/g, " ")
.trim();
}
/** แยกคำค้นเป็น token — คืนอาร์เรย์ว่างเมื่อไม่มีอะไรให้ค้น */
export function searchTokens(query: string): string[] {
const normalized = normalizeSearchText(query);
if (normalized === "") return [];
return normalized.split(" ").filter((token) => token !== "");
}
/**
* กลุ่มฟิลด์ที่ค้น + น้ำหนัก
* ชื่อโรงสำคัญที่สุด รองลงมาสถานที่/หมวด และรายละเอียดเป็นตัวสุดท้าย
*/
export const FIELD_WEIGHTS = {
names: 400,
place: 180,
categories: 150,
details: 60,
} as const;
export type FieldGroup = keyof typeof FIELD_WEIGHTS;
/**
* ระดับความตรง — คูณกับน้ำหนักของกลุ่มฟิลด์
* | ระดับ | ค่า | ตัวอย่าง (ค้น "house") |
* |------------------|-------|-----------------------------------|
* | เท่ากันทั้งค่า | 3 | ฟิลด์ = "house" |
* | ขึ้นต้นด้วยคำ | 2 | "house cinema samyan" |
* | มีคำอยู่ข้างใน | 1.2 | "the house of films" |
* | แบบหลวม (ตัดวรรณยุกต์) | 0.8 | "เฮ้าส์" จับคู่ "เฮาส" |
* | ไม่ตรง | 0 | — |
*/
export const MATCH_LEVEL = {
exact: 3,
prefix: 2,
contains: 1.2,
loose: 0.8,
} as const;
/** ฟิลด์หนึ่งฟิลด์ที่เตรียมไว้เทียบแล้ว (แปลงครั้งเดียว ใช้ได้ทุกคำค้น) */
export type IndexedField = {
group: FieldGroup;
exact: string;
loose: string;
};
/**
* รวมข้อความทุกจุดที่ผู้ใช้เห็น (ชื่อ/สถานที่/หมวด/รายละเอียด) แล้วแปลงล่วงหน้า
* เรียกครั้งเดียวต่อโรง แล้วนำผลไปให้คะแนนได้หลาย token โดยไม่ต้องแปลงซ้ำ
*/
export function buildSearchIndex(
cinema: Cinema,
tagLabels: Record<string, string> = {},
): IndexedField[] {
const raw: Record<FieldGroup, string[]> = {
names: [cinema.name, cinema.name_th ?? "", cinema.slug.replace(/-/g, " ")],
place: [
cinema.location_label,
cinema.location_label_en ?? "",
...(cinema.address_lines ?? []),
...(cinema.address_lines_en ?? []),
...cinema.transport.flatMap((mode) => [mode.value, mode.value_en ?? ""]),
],
categories: [
...cinema.tags,
...cinema.tags.map((tag) => tagLabels[tag] ?? ""),
],
details: [
cinema.description,
cinema.description_en ?? "",
...cinema.contacts.flatMap((contact) => [contact.label, contact.value]),
],
};
const index: IndexedField[] = [];
for (const group of Object.keys(raw) as FieldGroup[]) {
for (const value of raw[group]) {
if (value.trim() === "") continue;
index.push({
group,
exact: normalizeSearchText(value),
loose: foldSearchText(value),
});
}
}
return index;
}
/** ความตรงของ "หนึ่งฟิลด์กับหนึ่งคำค้น" — คืน 0 เมื่อไม่ตรง */
function matchLevel(
field: IndexedField,
token: string,
looseToken: string,
): number {
if (field.exact === token) return MATCH_LEVEL.exact;
if (field.exact.startsWith(token)) return MATCH_LEVEL.prefix;
if (field.exact.includes(token)) return MATCH_LEVEL.contains;
if (looseToken !== "" && field.loose.includes(looseToken)) {
return MATCH_LEVEL.loose;
}
return 0;
}
/**
* ให้คะแนนโรงหนึ่งกับคำค้น (0 = ไม่ตรง)
* ทุกคำต้องเจออย่างน้อยหนึ่งฟิลด์ (AND) แล้วนำคะแนนของแต่ละคำมารวมกัน
*/
export function scoreCinema(
cinema: Cinema,
tokens: string[],
tagLabels: Record<string, string> = {},
): number {
if (tokens.length === 0) return 0;
const index = buildSearchIndex(cinema, tagLabels);
let total = 0;
for (const token of tokens) {
const looseToken = foldSearchText(token);
let bestForToken = 0;
for (const field of index) {
const level = matchLevel(field, token, looseToken);
if (level === 0) continue;
bestForToken = Math.max(bestForToken, FIELD_WEIGHTS[field.group] * level);
}
if (bestForToken === 0) return 0;
total += bestForToken;
}
return total;
}
/**
* กรอง + เรียงผลลัพธ์
* - ไม่มีคำค้น → คงลำดับเดิม (ลำดับรายวัน/ยอดนิยม) แล้วกรองแค่หมวด
* - มีคำค้น → เรียงจากคะแนนมากไปน้อย (คะแนนเท่ากันคงลำดับเดิม)
*/
export function filterCinemas(
cinemas: Cinema[],
{
category,
query,
tagLabels = {},
}: {
category: CinemaCategory;
query: string;
/** ป้ายหมวดตามภาษาที่แสดงบนการ์ด (messages.tags) */
tagLabels?: Record<string, string>;
},
): Cinema[] {
const inCategory = cinemas.filter((cinema) => hasCategory(cinema, category));
const tokens = searchTokens(query);
if (tokens.length === 0) return inCategory;
return inCategory
.map((cinema, index) => ({
cinema,
index,
score: scoreCinema(cinema, tokens, tagLabels),
}))
.filter((row) => row.score > 0)
.sort((a, b) => b.score - a.score || a.index - b.index)
.map((row) => row.cinema);
}
+211
View File
@@ -0,0 +1,211 @@
/**
* ตัวช่วยสร้าง meta / JSON-LD ให้ทุก route (SEO พื้นฐาน)
*
* ทุกฟังก์ชันคืน "meta descriptor" ของ React Router — ใช้ได้ทั้ง SSR และตอนสลับหน้า
* ค่าที่ crawler เห็นจึงเหมือนกันทุกครั้ง (ไม่พึ่ง JavaScript ฝั่ง client)
*/
import type { MetaDescriptor } from "react-router";
import { SITE } from "@/lib/site";
/** เติมโดเมนให้พาธ — canonical/OG ต้องเป็น URL เต็มเสมอ */
export function absoluteUrl(origin: string, path: string): string {
const suffix = path.startsWith("/") ? path : `/${path}`;
return `${origin.replace(/\/+$/, "")}${suffix}`;
}
type MetaMatch = { id?: string; data?: unknown };
/** อ่าน origin ที่ root loader คำนวณไว้ (ใช้ใน meta() ของ route ลูก) */
export function originFromMatches(
matches: Array<MetaMatch> | undefined,
): string {
if (!matches) return "";
// ไม่ยึด id ของ root — เอา match แรกที่มี siteUrl (framework เปลี่ยน id ได้)
for (const match of matches) {
const data = match.data as { siteUrl?: unknown } | undefined;
if (typeof data?.siteUrl === "string" && data.siteUrl !== "")
return data.siteUrl;
}
return "";
}
type PageMetaInput = {
/** origin ของคำขอ เช่น `https://alterflixhub.hobbypj.com` (ห้ามฮาร์ดโค้ด) */
origin: string;
title: string;
description: string;
/** พาธของหน้านั้น ๆ เช่น `/about` หรือ `/cinema/lido-connect` */
path: string;
/** og:type — `article` สำหรับหน้าบทความ, `website` สำหรับหน้าทั่วไป */
type?: "website" | "article";
/** true = ไม่ให้ index (เช่นหน้าหลังบ้าน) */
noIndex?: boolean;
};
/** meta ชุดมาตรฐานของหนึ่งหน้า: title, description, canonical, OG, Twitter */
export function pageMeta({
origin,
title,
description,
path,
type = "website",
noIndex = false,
}: PageMetaInput): MetaDescriptor[] {
const url = absoluteUrl(origin, path);
const image = absoluteUrl(origin, SITE.ogImage);
return [
{ title },
{ name: "description", content: description },
{
name: "robots",
content: noIndex
? "noindex, nofollow"
: "index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1",
},
{ tagName: "link", rel: "canonical", href: url },
{ property: "og:type", content: type },
{ property: "og:site_name", content: SITE.name },
{ property: "og:locale", content: SITE.locale },
{ property: "og:title", content: title },
{ property: "og:description", content: description },
{ property: "og:url", content: url },
{ property: "og:image", content: image },
{ property: "og:image:width", content: "1200" },
{ property: "og:image:height", content: "630" },
{ property: "og:image:alt", content: SITE.name },
{ name: "twitter:card", content: "summary_large_image" },
{ name: "twitter:title", content: title },
{ name: "twitter:description", content: description },
{ name: "twitter:image", content: image },
];
}
/** JSON-LD ของเว็บไซต์ + องค์กร (ใส่ที่หน้าแรกครั้งเดียว) */
export function websiteJsonLd(origin: string): MetaDescriptor[] {
return [
{
"script:ld+json": {
"@context": "https://schema.org",
"@graph": [
{
"@type": "WebSite",
"@id": `${origin}/#website`,
url: `${origin}/`,
name: SITE.name,
description: SITE.description,
inLanguage: "th-TH",
publisher: { "@id": `${origin}/#organization` },
potentialAction: {
"@type": "SearchAction",
target: `${origin}/?q={search_term_string}`,
"query-input": "required name=search_term_string",
},
},
{
"@type": "Organization",
"@id": `${origin}/#organization`,
name: SITE.name,
url: `${origin}/`,
logo: absoluteUrl(origin, "/icon-512.png"),
},
],
},
},
];
}
/** JSON-LD breadcrumb ของหน้า (ช่วยให้ Google แสดงเส้นทางในผลค้นหา) */
export function breadcrumbJsonLd(
origin: string,
items: Array<{ name: string; path: string }>,
): MetaDescriptor[] {
return [
{
"script:ld+json": {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
itemListElement: items.map((item, index) => ({
"@type": "ListItem",
position: index + 1,
name: item.name,
item: absoluteUrl(origin, item.path),
})),
},
},
];
}
/** JSON-LD ของหน้าโรงหนัง — MovieTheater + ที่ตั้ง + พิกัด */
export function cinemaJsonLd(input: {
origin: string;
name: string;
description: string;
path: string;
image?: string | null;
coordinates?: { latitude: number; longitude: number } | null;
locationLabel?: string;
mapUrl?: string | null;
}): MetaDescriptor[] {
const image = input.image && input.image.trim() !== "" ? input.image : null;
return [
{
"script:ld+json": {
"@context": "https://schema.org",
"@type": "MovieTheater",
name: input.name,
description: input.description,
url: absoluteUrl(input.origin, input.path),
...(image
? {
image: image.startsWith("http")
? image
: absoluteUrl(input.origin, image),
}
: {}),
...(input.coordinates
? {
geo: {
"@type": "GeoCoordinates",
latitude: input.coordinates.latitude,
longitude: input.coordinates.longitude,
},
}
: {}),
address: {
"@type": "PostalAddress",
addressCountry: "TH",
...(input.locationLabel
? { streetAddress: input.locationLabel }
: {}),
},
...(input.mapUrl ? { hasMap: input.mapUrl } : {}),
},
},
];
}
/** JSON-LD ของหน้าบทความ (สำหรับโรงหนัง / สำหรับคนรักหนัง) */
export function articleJsonLd(input: {
origin: string;
headline: string;
description: string;
path: string;
}): MetaDescriptor[] {
return [
{
"script:ld+json": {
"@context": "https://schema.org",
"@type": "Article",
headline: input.headline,
description: input.description,
inLanguage: "th-TH",
mainEntityOfPage: absoluteUrl(input.origin, input.path),
author: { "@type": "Organization", name: SITE.name },
publisher: { "@type": "Organization", name: SITE.name },
},
},
];
}
+27
View File
@@ -0,0 +1,27 @@
import { createContext, useContext, type ReactNode } from "react";
/**
* โดเมนที่ใช้ในลิงก์แชร์ (มาจาก env `SHARE_ORIGIN` ผ่าน loader ที่ root)
*
* ค่าเริ่มต้นเป็นสตริงว่าง = ให้ปุ่มแชร์ใช้ origin ของหน้าที่เปิดอยู่
* แยกเป็น context เพื่อไม่ให้ component ต้องรู้จัก loader/route ของ root
*/
const ShareOriginContext = createContext<string>("");
export function ShareOriginProvider({
origin,
children,
}: {
origin: string;
children: ReactNode;
}) {
return (
<ShareOriginContext.Provider value={origin}>
{children}
</ShareOriginContext.Provider>
);
}
export function useShareOrigin(): string {
return useContext(ShareOriginContext);
}
+90
View File
@@ -0,0 +1,90 @@
import { describe, expect, it, vi } from "vitest";
import {
buildShareUrl,
buildShortSharePath,
resolveShareOrigin,
shareOrCopy,
} from "./share";
describe("buildShareUrl", () => {
it("ต่อ origin กับ path และตัด / ซ้ำท้าย origin", () => {
expect(buildShareUrl("https://alterflixhub.com/", "/cinema/lido")).toBe(
"https://alterflixhub.com/cinema/lido",
);
expect(buildShareUrl("http://localhost:8080", "cinema/lido")).toBe(
"http://localhost:8080/cinema/lido",
);
});
it("คงพาธที่มีภาษาไทยไว้ตามเดิม", () => {
expect(buildShareUrl("https://x.test", "/cinema/เมืองทองรามา")).toBe(
"https://x.test/cinema/เมืองทองรามา",
);
});
});
describe("resolveShareOrigin", () => {
it("ใช้โดเมนที่ตั้งไว้ และตัด / ท้ายออก", () => {
expect(
resolveShareOrigin(
"https://alterflixhub.hobbypj.com/",
"http://localhost:8080",
),
).toBe("https://alterflixhub.hobbypj.com");
});
it("ไม่ได้ตั้ง (ว่าง/undefined) → ใช้ origin ของหน้าเว็บ", () => {
expect(resolveShareOrigin("", "http://localhost:8080")).toBe(
"http://localhost:8080",
);
expect(resolveShareOrigin(undefined, "http://localhost:8080")).toBe(
"http://localhost:8080",
);
expect(resolveShareOrigin(" ", "http://localhost:8080")).toBe(
"http://localhost:8080",
);
});
});
describe("buildShortSharePath", () => {
it("สร้างลิงก์ย่อ /c/<slug>", () => {
expect(buildShortSharePath("kku-cinema")).toBe("/c/kku-cinema");
});
});
describe("shareOrCopy", () => {
const data = { title: "LIDO CONNECT", url: "https://x.test/cinema/lido" };
it("มี navigator.share → เรียกแผงแชร์ แล้วคัดลอกสำรองด้วย คืน shared", async () => {
const share = vi.fn().mockResolvedValue(undefined);
const writeText = vi.fn().mockResolvedValue(undefined);
expect(await shareOrCopy(data, { share, writeText })).toBe("shared");
expect(share).toHaveBeenCalledWith({ title: data.title, url: data.url });
expect(writeText).toHaveBeenCalledWith(data.url);
});
it("ไม่มี navigator.share → คัดลอกแล้วคืน copied", async () => {
const writeText = vi.fn().mockResolvedValue(undefined);
expect(await shareOrCopy(data, { writeText })).toBe("copied");
expect(writeText).toHaveBeenCalledWith(data.url);
});
it("ผู้ใช้ยกเลิกแผงแชร์ แต่คัดลอกได้ → ยังคืน shared", async () => {
const share = vi.fn().mockRejectedValue(new Error("AbortError"));
const writeText = vi.fn().mockResolvedValue(undefined);
expect(await shareOrCopy(data, { share, writeText })).toBe("shared");
});
it("clipboard ใช้ไม่ได้ → ตกไปใช้ legacyCopy", async () => {
const writeText = vi.fn().mockRejectedValue(new Error("denied"));
const legacyCopy = vi.fn().mockReturnValue(true);
expect(await shareOrCopy(data, { writeText, legacyCopy })).toBe("copied");
expect(legacyCopy).toHaveBeenCalledWith(data.url);
});
it("ทุกทางล้มเหลว → failed", async () => {
expect(await shareOrCopy(data, {})).toBe("failed");
});
});
+120
View File
@@ -0,0 +1,120 @@
/**
* ตัวช่วยแชร์ลิงก์โรงหนัง
*
* หลักการ: สร้างลิงก์จาก `origin + path` ตอนกดแชร์เท่านั้น (ไม่ฝังชื่อโดเมนไว้ในโค้ด)
* → เปลี่ยนโดเมน/ย้ายโฮสต์ทีหลัง ลิงก์เก่ายังเปิดได้ และลิงก์ที่ได้สั้นที่สุด
* (หน้า `/cinema/<slug>` ระบุโรงได้ครบอยู่แล้ว จึงไม่ต้องมี query เพิ่ม)
*/
/** ผลลัพธ์ที่เอาไปแสดงให้ผู้ใช้ */
export type ShareResult = "shared" | "copied" | "failed";
type ShareEnv = {
/** navigator.share (มีบนมือถือ/เดสก์ท็อปที่รองรับ Web Share) */
share?: (data: {
title: string;
text?: string;
url: string;
}) => Promise<void>;
/** navigator.clipboard.writeText */
writeText?: (text: string) => Promise<void>;
/** ทางสำรองสำหรับorigin ที่ไม่ใช่ HTTPS — คืน true ถ้าคัดลอกสำเร็จ */
legacyCopy?: (text: string) => boolean;
};
/** รวม origin + path เป็นลิงก์เต็ม (ตัด `/` ซ้ำท้าย origin) */
export function buildShareUrl(origin: string, path: string): string {
const base = origin.replace(/\/+$/, "");
const suffix = path.startsWith("/") ? path : `/${path}`;
return `${base}${suffix}`;
}
/**
* โดเมนที่ใช้ในลิงก์แชร์
* ตั้งได้ผ่าน env `SHARE_ORIGIN` (เช่น https://alterflixhub.hobbypj.com)
* ถ้าไม่ได้ตั้ง ใช้ origin ของหน้าที่กำลังเปิดอยู่ (ใช้ตอน dev ได้ตามปกติ)
*/
export function resolveShareOrigin(
configured: string | null | undefined,
fallbackOrigin: string,
): string {
const value = (configured ?? "").trim();
return (value === "" ? fallbackOrigin : value).replace(/\/+$/, "");
}
/**
* ลิงก์ย่อของโรงหนัง: `/c/<slug>` (route นี้ redirect ไปหน้าเต็ม `/cinema/<slug>`)
* ไม่ encode slug เพราะ slug เป็น ASCII/ไทยที่ปลอดภัยอยู่แล้ว — encode จะทำให้ลิงก์ยาวและอ่านไม่ออก
*/
export function buildShortSharePath(slug: string): string {
return `/c/${slug}`;
}
/**
* ทางสำรองสุดท้ายเมื่อ Clipboard API ใช้ไม่ได้ (เช่น http ธรรมดา)
* ใช้ <textarea> ที่ซ่อนไว้ + execCommand("copy")
*/
function legacyCopy(text: string): boolean {
if (typeof document === "undefined") return false;
const area = document.createElement("textarea");
area.value = text;
area.setAttribute("readonly", "");
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
let copied = false;
try {
copied = document.execCommand("copy");
} catch {
copied = false;
}
document.body.removeChild(area);
return copied;
}
/** อ่านความสามารถของเบราว์เซอร์ปัจจุบัน (แยกออกมาเพื่อเทสต์ได้) */
function defaultEnv(): ShareEnv {
if (typeof navigator === "undefined") return {};
const nav = navigator as Navigator & {
share?: ShareEnv["share"];
clipboard?: { writeText?: (text: string) => Promise<void> };
};
return {
share: typeof nav.share === "function" ? nav.share.bind(nav) : undefined,
writeText:
typeof nav.clipboard?.writeText === "function"
? nav.clipboard.writeText.bind(nav.clipboard)
: undefined,
legacyCopy,
};
}
/**
* แชร์ลิงก์: ใช้แผงแชร์ของระบบถ้ามี แล้วคัดลอกลงคลิปบอร์ดเป็นทางเลือกให้เดสก์ท็อปเสมอ
* ลำดับ: navigator.share → clipboard → textarea/execCommand → failed
*/
export async function shareOrCopy(
data: { title: string; url: string },
env: ShareEnv = defaultEnv(),
): Promise<ShareResult> {
if (env.share) {
try {
await env.share({ title: data.title, url: data.url });
} catch {
// ผู้ใช้กดยกเลิกแผงแชร์ หรือเบราว์เซอร์ปฏิเสธ → ไม่ถือว่าพัง ให้ลองคัดลอกต่อ
}
}
if (env.writeText) {
try {
await env.writeText(data.url);
return env.share ? "shared" : "copied";
} catch {
// ตกไปใช้ทางสำรองด้านล่าง
}
}
if (env.legacyCopy?.(data.url)) return env.share ? "shared" : "copied";
return "failed";
}
+42
View File
@@ -0,0 +1,42 @@
/**
* ข้อมูลระดับเว็บไซต์ (แหล่งเดียว) — ใช้โดย SEO, sitemap, robots และ JSON-LD
*
* **ไม่เก็บโดเมนไว้ในโค้ด**: origin มาจาก request จริง (`app/lib/request-origin.ts`)
* ถ้าจำเป็นต้องบังคับโดเมน (เช่น dev หลัง proxy แปลก ๆ) ค่อยตั้ง env `SITE_URL`
*/
import { normalizeOrigin } from "@/lib/request-origin";
export const SITE = {
name: "AlterFlixHub",
/** ใช้เป็นค่าเริ่มต้นของ <title> (หน้าแรก) */
title: "AlterFlixHub — โรงหนังอิสระ อาร์ตเฮาส์ และกลุ่มคนฉายหนังในไทย",
description:
"รวมโรงหนังอิสระและอาร์ตเฮาส์ในประเทศไทยไว้ที่เดียว พร้อมที่ตั้ง วิธีเดินทาง สิ่งอำนวยความสะดวก และปุ่มหาภาพยนตร์โรงใกล้ฉัน",
locale: "th_TH",
ogImage: "/og/alterflixhub-1200x630.png",
/** หน้าแบบ static ที่ควรอยู่ใน sitemap (หน้าโรงหนังมาจากข้อมูลจริง) */
staticPages: [
{ path: "/", priority: "1.0", changeFrequency: "daily" as const },
{
path: "/for-film-lovers",
priority: "0.7",
changeFrequency: "monthly" as const,
},
{
path: "/for-cinemas",
priority: "0.7",
changeFrequency: "monthly" as const,
},
{ path: "/about", priority: "0.5", changeFrequency: "yearly" as const },
],
} as const;
/**
* โดเมนที่บังคับผ่าน env — คืน "" ถ้าไม่ได้ตั้ง (กรณีปกติ)
* `SITE_URL` มาก่อน แล้วค่อย `SHARE_ORIGIN` (ใช้ร่วมกันเพื่อไม่ต้องตั้งซ้ำ)
*/
export function configuredOrigin(): string {
// guard:allow-no-env-credentials — โดเมนสาธารณะ ไม่ใช่ข้อมูลลับ
const raw = process.env.SITE_URL ?? process.env.SHARE_ORIGIN ?? "";
return normalizeOrigin(raw);
}
+70
View File
@@ -0,0 +1,70 @@
/**
* ทดสอบ sitemap.xml — กันกรณี "crawler เปิดได้แต่ได้ไฟล์ผิด"
* (ไม่มีโรงที่ hidden, URL เป็นโดเมน production, XML ถูกต้อง)
*/
import { describe, expect, it } from "vitest";
import type { Cinema } from "@/lib/cinemas";
import { SITE } from "@/lib/site";
/** origin ปลอมสำหรับทดสอบ (โค้ดจริงหาจาก request) */
const ORIGIN = "https://example.test";
import { buildSitemapXml, sitemapLocation } from "@/lib/sitemap";
function cinema(slug: string, hidden = false): Cinema {
return {
slug,
name: slug,
tags: [],
location_label: "",
coordinates: null,
description: "",
map_url: null,
address_lines: [],
transport: [],
contacts: [],
payments: [],
photos: [],
...(hidden ? { hidden: true } : {}),
} as Cinema;
}
describe("sitemapLocation", () => {
it("หน้าแรกต้องมี / ปิดท้าย", () => {
expect(sitemapLocation(ORIGIN, "/")).toBe(`${ORIGIN}/`);
});
it("พาธอื่นต่อท้ายโดเมนตรง ๆ", () => {
expect(sitemapLocation(ORIGIN, "/about")).toBe(`${ORIGIN}/about`);
expect(sitemapLocation(ORIGIN, "about")).toBe(`${ORIGIN}/about`);
});
});
describe("buildSitemapXml", () => {
it("มีหน้า static ครบตาม SITE.staticPages", () => {
const xml = buildSitemapXml(ORIGIN, []);
for (const page of SITE.staticPages) {
expect(xml).toContain(`<loc>${sitemapLocation(ORIGIN, page.path)}</loc>`);
}
expect(xml.startsWith('<?xml version="1.0" encoding="UTF-8"?>')).toBe(true);
expect(xml).toContain("</urlset>");
});
it("เพิ่มหน้าโรงหนัง และข้ามโรงที่ hidden", () => {
const xml = buildSitemapXml(ORIGIN, [
cinema("visible-cinema"),
cinema("secret", true),
]);
expect(xml).toContain(`${ORIGIN}/cinema/visible-cinema`);
expect(xml).not.toContain("secret");
});
it("ไม่ปล่อย localhost ลงใน sitemap", () => {
expect(buildSitemapXml(ORIGIN, [cinema("x")])).not.toContain("localhost");
});
it("escape อักขระ XML ใน slug", () => {
const xml = buildSitemapXml(ORIGIN, [cinema("a&b")]);
expect(xml).toContain("a&amp;b");
});
});
+66
View File
@@ -0,0 +1,66 @@
/**
* ตัวสร้าง sitemap.xml (ฟังก์ชันบริสุทธิ์ — ทดสอบได้โดยไม่ต้องมีเซิร์ฟเวอร์)
*
* หน้า static มาจาก `SITE.staticPages` · หน้าโรงหนังมาจากข้อมูลจริง
* (ไม่รวมโรงที่ตั้ง `hidden: true` เพราะไม่ควรอยู่ในผลค้นหา)
*/
import type { Cinema } from "@/lib/cinemas";
import { SITE } from "@/lib/site";
function escapeXml(value: string): string {
return value
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}
/** ต่อพาธกับโดเมน — หน้าแรกต้องมี `/` ปิดท้าย */
export function sitemapLocation(origin: string, path: string): string {
const base = origin.replace(/\/+$/, "");
if (path === "/" || path === "") return `${base}/`;
return `${base}${path.startsWith("/") ? path : `/${path}`}`;
}
function urlEntry(
origin: string,
path: string,
options: { priority: string; changeFrequency: string },
): string {
return [
" <url>",
` <loc>${escapeXml(sitemapLocation(origin, path))}</loc>`,
` <changefreq>${options.changeFrequency}</changefreq>`,
` <priority>${options.priority}</priority>`,
" </url>",
].join("\n");
}
/** จำนวน URL สูงสุดต่อไฟล์ (ข้อกำหนด sitemap = 50,000) */
export function buildSitemapXml(origin: string, cinemas: Cinema[]): string {
const entries = SITE.staticPages.map((page) =>
urlEntry(origin, page.path, {
priority: page.priority,
changeFrequency: page.changeFrequency,
}),
);
for (const cinema of cinemas) {
if (cinema.hidden) continue;
entries.push(
urlEntry(origin, `/cinema/${cinema.slug}`, {
priority: "0.8",
changeFrequency: "weekly",
}),
);
}
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
...entries,
"</urlset>",
"",
].join("\n");
}