165 lines
5.3 KiB
TypeScript
165 lines
5.3 KiB
TypeScript
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"));
|
|
}
|