Files
web-alterflixhub/app/routes/_index.tsx
T
Bkk1234 1932098a1d feat(home): ชั้นกรองที่ 1 — ประเภทโรงหนัง (ท้องถิ่น / อินดี้ / กลุ่มคนฉายหนัง)
- แถบกรองสองชั้นในแถวเดียว: ทั้งหมด → 3 ประเภท │ ยอดนิยม → หมวดภาพยนตร์เดิม
- เก็บประเภทที่ฟิลด์เดี่ยว cinema.venue_type (ค่าเดียว) + hasVenue()/filterCinemas({ venue })
- ย้าย "กลุ่มคนฉายหนัง" จาก categories ขึ้นชั้น 1 (ไม่ให้ปุ่มซ้ำ) · tag ยังอยู่และยังค้นหาเจอ
- เลือกได้ทีละชั้น: กดประเภทล้างหมวด / กดหมวดล้างประเภท / ทั้งหมดล้างทั้งคู่
- ปิด popularity path เมื่อกรองด้วยประเภท (กันจัดอันดับข้ามประเภท)
- หลังบ้าน: ช่อง "ประเภทโรงหนัง" ในหมวดข้อมูลหลัก + sanitize เฉพาะค่าใน VENUE_TYPES
- i18n: messages.venues (TH/EN) · override ได้ผ่าน site.terms
- scripts/set-venue-types.mjs จัดประเภท 29 โรง (15 ท้องถิ่น / 11 อินดี้ / 3 กลุ่มคนฉายหนัง) พร้อมสำรอง content.json
- tests: hasVenue + filterCinemas (165 ผ่าน) · sw v2.0.5 · DESIGN/AGENTS/README/admin-guide/api อัปเดต
2026-11-16 01:46:59 +07:00

230 lines
9.0 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { useLoaderData, useSearchParams } from "react-router";
import { HeroSection } from "@/components/home/HeroSection";
import { CategoryFilter, CinemaGrid } from "@/components/site/CinemaGrid";
import { Reveal } from "@/components/site/Reveal";
import { SiteShell } from "@/components/site/SiteShell";
import { useNearMe } from "@/hooks/use-near-me";
import { trackEvent } from "@/lib/analytics-client";
import { APP_TITLE } from "@/lib/app-config";
import {
CINEMA_CATEGORIES,
DEFAULT_CATEGORY,
VENUE_TYPES,
publiclyVisible,
type Cinema,
type CinemaCategory,
type VenueType,
} from "@/lib/cinemas";
import { useContent } from "@/lib/content-context";
import { dailyOrder, dayKey } from "@/lib/daily-order";
import { sortByDistance } from "@/lib/geo";
import { useI18n } from "@/lib/i18n";
import { DEFAULT_LOCALE, MESSAGES } from "@/lib/i18n/messages";
import { scrollIntoViewRespectMotion } from "@/lib/motion";
import { resolvePageOrigin } from "@/lib/page-origin";
import { computePopularity } from "@/lib/popularity.server";
import { filterCinemas } from "@/lib/search";
import { pageMeta, originFromMatches, websiteJsonLd } from "@/lib/seo";
import { SITE } from "@/lib/site";
/** head (title/description) ไม่เปลี่ยนตามภาษา — meta() ไม่มี access ต่อ cookie */
const HEAD_MESSAGES = MESSAGES[DEFAULT_LOCALE];
/** meta() ของ route ลูกอ่าน origin ที่ root loader หาไว้ (ไม่ฝังโดเมน) */
type MetaArgs = { matches?: Array<{ id?: string; data?: unknown }> };
export function meta({
loaderData,
matches,
}: MetaArgs & { loaderData?: { origin?: string } }) {
const origin = loaderData?.origin ?? originFromMatches(matches);
return [
...pageMeta({
origin,
title: SITE.title,
description: HEAD_MESSAGES.meta.homeDescription,
path: "/",
}),
...websiteJsonLd(origin),
];
}
/** จำนวนการ์ดที่แสดงก่อนกด "แสดงเพิ่ม" */
const INITIAL_VISIBLE = 4;
/** อันดับยอดนิยม + คีย์วันที่สำหรับสลับลำดับการ์ด (memo 5 นาที) — ส่งมากับ loader */
export async function loader({ request }: { request: Request }) {
return {
popularity: await computePopularity(),
orderKey: dayKey(),
origin: resolvePageOrigin(request),
};
}
export default function HomeRoute() {
const { messages, locale } = useI18n();
const { popularity, orderKey } = useLoaderData<typeof loader>();
const { cinemas } = useContent();
const { status: nearMeStatus, distances, requestLocation } = useNearMe();
const [category, setCategory] = useState<CinemaCategory>(DEFAULT_CATEGORY);
/** ชั้นกรองที่ 1 — ประเภทโรงหนัง (null = ทุกประเภท) */
const [venue, setVenue] = useState<VenueType | null>(null);
// รองรับลิงก์ค้นหาตรง ๆ (/?q=...) — ให้ SearchAction ใน JSON-LD ทำงานจริง
const [searchParams] = useSearchParams();
const [query, setQuery] = useState(() => searchParams.get("q") ?? "");
const [showAll, setShowAll] = useState(false);
/** หัวข้อผลลัพธ์ — ใช้เป็นจุดเลื่อนเมื่อกดปุ่ม "ค้นหา" หรือ Enter */
const resultsRef = useRef<HTMLElement | null>(null);
const matched = useMemo(() => {
// ลำดับการ์ดสลับทุกวัน (ไม่ให้โรงใดอยู่ตำแหน่งเดิมสองวันติดกัน)
const base = dailyOrder(
publiclyVisible(cinemas),
(cinema) => cinema.slug,
orderKey,
);
const byStats =
category === "ยอดนิยม" &&
venue === null &&
popularity.ready &&
query.trim() === "";
if (!byStats)
return filterCinemas(base, {
category,
query,
venue,
tagLabels: messages.tags,
});
// ใช้เฉพาะโรงที่ยังไม่ถูกซ่อน และเรียงตามอันดับสถิติ
const bySlug = new Map(base.map((cinema) => [cinema.slug, cinema]));
return popularity.slugs
.map((slug) => bySlug.get(slug))
.filter((cinema): cinema is Cinema => cinema !== undefined);
}, [cinemas, category, query, venue, popularity, orderKey, messages.tags]);
// เรียงจากใกล้สุดไปไกลสุดเมื่อทราบตำแหน่งแล้ว (ไม่กรองตามรัศมี — ไกลแค่ไหนก็ยังแสดง)
const ordered =
nearMeStatus === "ready" ? sortByDistance(matched, distances) : matched;
const visibleCinemas = showAll ? ordered : ordered.slice(0, INITIAL_VISIBLE);
const hasMore = ordered.length > visibleCinemas.length;
const keyword = query.trim();
// เก็บสถิติการค้นหา: ยิงครั้งเดียวหลังผู้ใช้หยุดพิมพ์ 900ms และมีคำค้นอย่างน้อย 2 ตัวอักษร
useEffect(() => {
if (keyword.length < 2) return;
const timer = setTimeout(() => {
trackEvent({
type: "search",
query: keyword,
category,
result_count: matched.length,
locale,
});
}, 900);
return () => clearTimeout(timer);
}, [keyword, category, matched.length, locale]);
/**
* ปุ่ม "ค้นหา" / Enter — ผลลัพธ์ถูกกรองสดอยู่แล้วขณะพิมพ์
* จึงทำหน้าที่แค่พาผู้ใช้ไปดูผล (ปิดคีย์บอร์ดมือถือทำที่ HeroSection)
*/
function handleSubmitSearch() {
scrollIntoViewRespectMotion(resultsRef.current);
}
function handleRequestLocation() {
requestLocation();
trackEvent({
type: "near_me",
category,
query: keyword || undefined,
result_count: matched.length,
locale,
});
}
return (
<SiteShell variant="home">
<main className="relative z-10 mx-auto max-w-[1440px] px-5 pb-12 md:px-[108px] md:pb-16">
<HeroSection
query={query}
onQueryChange={setQuery}
nearMeStatus={nearMeStatus}
onRequestLocation={handleRequestLocation}
onSubmitSearch={handleSubmitSearch}
/>
<section
ref={resultsRef}
className="mt-16 flex scroll-mt-[88px] flex-col gap-6 md:mt-[65px]"
>
<Reveal
delay={260}
className="flex min-h-[72px] items-center border-b border-[#1F1F1F] py-2"
>
<h2 className="text-[28px] font-semibold leading-[1.3]">
{messages.list.title}
</h2>
</Reveal>
<Reveal delay={340}>
<CategoryFilter
active={category}
categories={CINEMA_CATEGORIES}
onChange={setCategory}
venues={VENUE_TYPES}
activeVenue={venue}
onVenueChange={setVenue}
/>
</Reveal>
{visibleCinemas.length === 0 ? (
<p className="py-16 text-center text-sm text-[#B3B3B3]">
{messages.list.empty}
</p>
) : (
<div className="mt-2">
<CinemaGrid
cinemas={visibleCinemas}
source={keyword ? "search" : "category"}
searchQuery={keyword || undefined}
/>
</div>
)}
{hasMore ? (
<Reveal kind="fade" className="flex justify-center pt-2">
<button
type="button"
onClick={() => setShowAll(true)}
className="h-10 w-[220px] rounded-lg border border-[#8F0808] bg-[#8F0808] transition hover:bg-[#a30a0a]"
>
{messages.list.showMore}
</button>
</Reveal>
) : null}
{showAll && ordered.length > INITIAL_VISIBLE ? (
<Reveal kind="fade" className="flex justify-center pt-2">
<button
type="button"
onClick={() => {
setShowAll(false);
// ย่อกลับแล้วพาผู้ใช้ขึ้นไปที่หัวข้อผลลัพธ์ ไม่ให้ค้างอยู่ท้ายหน้า
scrollIntoViewRespectMotion(resultsRef.current);
}}
className="h-10 w-[220px] rounded-lg border border-[#303030] px-4 text-sm transition hover:border-[#A92626] hover:text-[#D47272]"
>
{messages.list.showLess}
</button>
</Reveal>
) : null}
</section>
</main>
</SiteShell>
);
}