fix(i18n): overhaul i18n with [locale] routing, SSR translations, and hreflang SEO

Rewrites the i18n system introduced in PR #94 to use Next.js App Router
[locale] dynamic segments with SSR-rendered translations and proper
middleware locale routing.

- Add middleware locale detection: / rewrites to /zh-CN/ internally,
  /en and /ja pass through, /zh-CN/... redirects to bare path
- Move all 7 pages under app/[locale]/ with SSR translation injection
- Fix server→client serialization: pre-evaluate function-valued
  translations (makeSerializable) to eliminate hydration flash
- Fix language switch key flash: use hard navigation with localStorage-
  only persistence, avoiding React state update before page reload
- Add <link rel="alternate" hreflang> tags for multilingual SEO
- Fix Supabase setAll overwriting locale rewrite response
- Trim locales from 22 to 3 (zh-CN/en/ja), delete 19 incomplete files
- LLM-translate 240 firstact game preset JSONs (en + ja, landscape +
  portrait) and story titles via gemini-3.5-flash
- Delete 11 one-off migration scripts and outdated i18n docs
- Add useLocalePath hook and navigation utilities

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
yuanzonghao
2026-06-18 23:16:17 +08:00
parent 941b54c3f8
commit 0a7076d5b9
301 changed files with 2447 additions and 4358 deletions
@@ -20,6 +20,7 @@ import {
downloadImagesAsZip,
inferImageExtension,
} from "@/lib/imageZipDownload";
import { useLocalePath } from "@/lib/i18n/hooks";
// ──────────────────────────────────────────────────────────────────────
// Gallery — an offline-only replay of a played session. Entered from
@@ -608,6 +609,7 @@ type Frame = {
};
function GalleryInner() {
const lp = useLocalePath();
const [doc, setDoc] = useState<GalleryDoc | null>(null);
const [missingId, setMissingId] = useState<string | null>(null);
const [importing, setImporting] = useState(false);
@@ -1068,7 +1070,7 @@ function GalleryInner() {
)}
<Link
href="/"
href={lp("/")}
className="mt-6 text-[10px] smallcaps text-clay-700 hover:text-ember-500 transition-colors inline-flex items-center gap-3"
>
<i className="fa-solid fa-arrow-left text-[9px]" />
@@ -1128,7 +1130,7 @@ function GalleryInner() {
style={{ paddingTop: "max(0.75rem, env(safe-area-inset-top))" }}
>
<Link
href="/"
href={lp("/")}
className="pointer-events-auto flex h-9 items-center gap-2 rounded-full bg-black/40 px-3 text-[11px] smallcaps text-white/80 backdrop-blur-sm transition-colors hover:text-white"
aria-label="返回"
>
+28
View File
@@ -0,0 +1,28 @@
import { notFound } from "next/navigation";
import { LOCALES, type Locale } from "@/lib/i18n/config";
import { loadTranslations } from "@/lib/i18n/server";
import { I18nProvider } from "@/lib/i18n/client";
import { isValidLocale } from "@/lib/i18n/utils";
export function generateStaticParams() {
return LOCALES.map((locale) => ({ locale }));
}
export default async function LocaleLayout({
children,
params,
}: {
children: React.ReactNode;
params: Promise<{ locale: string }>;
}) {
const { locale } = await params;
if (!isValidLocale(locale)) notFound();
const translations = await loadTranslations(locale as Locale);
return (
<I18nProvider initialLocale={locale as Locale} initialTranslations={translations}>
{children}
</I18nProvider>
);
}
+13 -2
View File
@@ -1,12 +1,23 @@
import Link from "next/link";
import { CustomForm } from "@/components/CustomForm";
import { localePath } from "@/lib/i18n/navigation";
import { isValidLocale } from "@/lib/i18n/utils";
import { DEFAULT_LOCALE, type Locale } from "@/lib/i18n/config";
export default async function NewPage({
params,
}: {
params: Promise<{ locale: string }>;
}) {
const { locale: rawLocale } = await params;
const locale: Locale = isValidLocale(rawLocale) ? rawLocale : DEFAULT_LOCALE;
const lp = (path: string) => localePath(path, locale);
export default function NewPage() {
return (
<div className="min-h-screen flex flex-col">
<header className="px-6 md:px-16 pt-7 md:pt-10 flex items-center justify-between">
<Link
href="/"
href={lp("/")}
className="text-[10px] smallcaps text-clay-700 hover:text-clay-900 transition-colors flex items-center gap-2"
>
<i className="fa-solid fa-arrow-left text-[9px]" />
+64 -23
View File
@@ -23,6 +23,7 @@ import { AuthModal } from "@/components/AuthModal";
import { UserChip } from "@/components/UserChip";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { useI18n } from "@/lib/i18n/client";
import { useLocalePath } from "@/lib/i18n/hooks";
// Option value → i18n key suffix maps. The Chinese strings from lib/options.ts
// stay as the underlying identifier (so analytics unions and STYLE_MAP keys
@@ -813,6 +814,33 @@ function buildFallbackCards(g: Gender): FeaturedCard[] {
});
}
type StoriesI18n = { male: StoryContent[]; female: StoryContent[] };
async function loadStoriesI18n(locale: string): Promise<StoriesI18n | null> {
if (locale === "zh-CN") return null;
try {
const mod = locale === "en"
? await import("@/lib/i18n/stories-en.json")
: locale === "ja"
? await import("@/lib/i18n/stories-ja.json")
: null;
return mod ? (mod.default as StoriesI18n) : null;
} catch { return null; }
}
function localizeCards(cards: FeaturedCard[], i18n: StoriesI18n | null): FeaturedCard[] {
if (!i18n) return cards;
return cards.map((card) => {
const m = card.id.match(/^([mf])(\d+)$/);
if (!m) return card;
const gender = m[1] === "f" ? "female" : "male";
const idx = parseInt(m[2]!, 10);
const translated = i18n[gender]?.[idx];
if (!translated) return card;
return { ...card, title: translated.title, outline: translated.outline };
});
}
/* ---------- typewriter ---------- */
// 父组件持有当前 phrase 的索引(这样 start() 不输入时能用当前闪动的那句
@@ -1418,6 +1446,7 @@ function StyleModal({
export default function HomePage() {
const router = useRouter();
const { t, locale, tArray } = useI18n();
const lp = useLocalePath();
const [sel, setSel] = useState<number[]>(OPTS.map((o) => o.defaultIndex ?? 0));
const [open, setOpen] = useState<number>(-1);
@@ -1483,7 +1512,6 @@ export default function HomePage() {
const optLabels = OPTS.map((o) => t(o.labelKey));
const phrasesKey = GENDER_KEYS[gender] ?? "male";
const phrases = tArray(`home.examples.${phrasesKey}`);
void locale;
// 当前 Typewriter 闪动到第几句——start() 空输入时会拿它做默认故事种子,
// 实现「所见即所玩」。切性向时重置,否则索引可能越界。
const [phraseIdx, setPhraseIdx] = useState(0);
@@ -1506,36 +1534,49 @@ export default function HomePage() {
// Featured stories 动态加载(从 /api/stories/featured),降级用硬编码 STORIES。
// 惰性初始化确保首屏即有卡片内容(SSR + hydration 一致),fetch 成功后无缝替换。
const storiesI18nRef = useRef<{ locale: string; data: StoriesI18n | null }>({ locale: "", data: null });
const [featuredCards, setFeaturedCards] = useState<FeaturedCard[]>(() =>
buildFallbackCards(galleryGender),
);
useEffect(() => {
const apiGender = galleryGender === "女性向" ? "female" : "male";
fetch(`/api/stories/featured?gender=${apiGender}`)
.then((r) => r.json())
.then((data: { stories: FeaturedStoryRow[] }) => {
let cancelled = false;
(async () => {
if (storiesI18nRef.current.locale !== locale) {
storiesI18nRef.current = { locale, data: await loadStoriesI18n(locale) };
}
const i18n = storiesI18nRef.current.data;
if (cancelled) return;
const apiGender = galleryGender === "女性向" ? "female" : "male";
try {
const r = await fetch(`/api/stories/featured?gender=${apiGender}`);
const data: { stories: FeaturedStoryRow[] } = await r.json();
// API 已按 sortOrder 排序且仅返回 isActive=1 的记录。
// D1 故障时 featured route 返回 { stories: [] }HTTP 200),
// 空数组也必须降级到常量,否则首页白屏。
const rows = data.stories ?? [];
if (cancelled) return;
if (rows.length === 0) {
setFeaturedCards(buildFallbackCards(galleryGender));
setFeaturedCards(localizeCards(buildFallbackCards(galleryGender), i18n));
return;
}
setFeaturedCards(
rows.map((s) => ({
id: s.id,
title: s.title,
outline: s.outline,
coverPath: s.coverPath,
})),
localizeCards(
rows.map((s) => ({
id: s.id,
title: s.title,
outline: s.outline,
coverPath: s.coverPath,
})),
i18n,
),
);
})
.catch(() => {
// 网络故障 / JSON 解析失败 → 降级到常量
setFeaturedCards(buildFallbackCards(galleryGender));
});
}, [galleryGender]);
} catch {
if (!cancelled) setFeaturedCards(localizeCards(buildFallbackCards(galleryGender), i18n));
}
})();
return () => { cancelled = true; };
}, [galleryGender, locale]);
/* close any open dropdown on outside click */
useEffect(() => {
@@ -1755,7 +1796,7 @@ export default function HomePage() {
"infiplot:custom",
JSON.stringify({ worldSetting, styleGuide, audioEnabled, styleReferenceImage, playerName: playerName || undefined }),
);
router.push("/play?custom=1");
router.push(lp("/play?custom=1"));
};
const handleStoryImport = async (file: File | undefined) => {
@@ -1790,7 +1831,7 @@ export default function HomePage() {
}
const doc = parseStoryShareDoc(JSON.parse(text));
window.sessionStorage.setItem(STORY_SHARE_STORAGE_KEY, JSON.stringify(doc));
router.push("/play?share=1");
router.push(lp("/play?share=1"));
} catch (e) {
setStoryImportError(e instanceof Error ? e.message : t("home.errors.parseFailed"));
} finally {
@@ -1823,7 +1864,7 @@ export default function HomePage() {
tts: audioEnabled,
card: cardId as `${"m" | "f"}${number}`,
});
router.push(`/play?card=${cardId}`);
router.push(lp(`/play?card=${cardId}`));
};
// overflow-x-hidden 在 wrapper 层兜底:body 的 overflow-x-hidden 在移动端会因
@@ -2107,9 +2148,9 @@ export default function HomePage() {
<div className="flex flex-col items-center gap-2 text-[10px] smallcaps text-clay-500">
<span>{t("home.about.copyright")}</span>
<span className="flex items-center gap-3 normal-case tracking-normal text-[11px]">
<a href="/privacy" className="hover:text-ember-500 transition-colors">{t("home.about.privacyPolicy")}</a>
<a href={lp("/privacy")} className="hover:text-ember-500 transition-colors">{t("home.about.privacyPolicy")}</a>
<span className="text-clay-300">·</span>
<a href="/terms" className="hover:text-ember-500 transition-colors">{t("home.about.terms")}</a>
<a href={lp("/terms")} className="hover:text-ember-500 transition-colors">{t("home.about.terms")}</a>
</span>
</div>
</footer>
@@ -16,7 +16,7 @@ import {
type Phase,
} from "@/components/PlayCanvas";
import type { DialogueHistoryItem } from "@/components/DialogueHistoryModal";
import type { GalleryDoc, GalleryScene } from "@/app/gallery/page";
import type { GalleryDoc, GalleryScene } from "@/app/[locale]/gallery/page";
import { SettingsModal, readStoredPlayerName, readStoredVisionClick } from "@/components/SettingsModal";
import { annotateClick } from "@/lib/annotateClient";
import { loadClientTtsConfig } from "@/lib/clientTtsConfig";
@@ -59,6 +59,7 @@ import { writeResumeSnapshot, consumeResumeSnapshot } from "@/lib/authResume";
import { AuthModal } from "@/components/AuthModal";
import { UserChip } from "@/components/UserChip";
import { useI18n } from "@/lib/i18n/client";
import { useLocalePath } from "@/lib/i18n/hooks";
const MUTED_STORAGE_KEY = "infiplot:muted";
// One-shot snapshot of in-progress game state, written just before an OAuth
@@ -605,6 +606,7 @@ function PlayInner() {
const router = useRouter();
const params = useSearchParams();
const { t, locale } = useI18n();
const lp = useLocalePath();
const [phase, setPhase] = useState<Phase>("loading-first");
const [session, setSession] = useState<Session | null>(null);
@@ -1703,7 +1705,7 @@ function PlayInner() {
const sessionLanguage: string = locale;
if (!cardName && !livePayload && !storyId) {
router.replace("/");
router.replace(lp("/"));
return;
}
@@ -1712,12 +1714,12 @@ function PlayInner() {
// TEMPORARY: localStorage-only mode (D1 disabled until auth integration)
const loadedSession = loadFromLocalStorage(storyId);
if (!loadedSession) {
setError("找不到保存的剧情");
setError(t("play.savedStoryNotFound"));
return;
}
const firstScene = loadedSession.history[0]?.scene;
if (!firstScene) {
setError("剧情数据损坏");
setError(t("play.savedStoryCorrupted"));
return;
}
(async () => {
@@ -1752,22 +1754,37 @@ function PlayInner() {
cardGender?: string;
};
const firstactDir = sessionOrientation === "portrait"
const baseDir = sessionOrientation === "portrait"
? "firstact-portrait"
: "firstact";
const localeSuffix = locale !== "zh-CN" ? `-${locale}` : "";
const firstactDir = `${baseDir}${localeSuffix}`;
const startT0 = Date.now();
const fetchStart: Promise<PrebakedFirstAct> = cardName
? fetch(`/home/${firstactDir}/${encodeURIComponent(cardName)}.json`).then(
async (r) => {
if (r.ok) return (await r.json()) as PrebakedFirstAct;
// Fallback chain: locale-specific → zh-CN portrait → zh-CN landscape
if (localeSuffix) {
const zhFb = await fetch(`/home/${baseDir}/${encodeURIComponent(cardName)}.json`);
if (zhFb.ok) return (await zhFb.json()) as PrebakedFirstAct;
}
if (sessionOrientation === "portrait") {
console.warn(`[play] portrait firstact missing for ${cardName} (HTTP ${r.status}), falling back to landscape`);
const fb = await fetch(`/home/firstact/${encodeURIComponent(cardName)}.json`);
const fbDir = localeSuffix ? `firstact-${locale}` : "firstact";
const fb = await fetch(`/home/${fbDir}/${encodeURIComponent(cardName)}.json`);
if (fb.ok) {
const fallback = (await fb.json()) as PrebakedFirstAct;
return { ...fallback, scene: { ...fallback.scene, orientation: "landscape" as const } };
}
if (localeSuffix) {
const zhLandscape = await fetch(`/home/firstact/${encodeURIComponent(cardName)}.json`);
if (zhLandscape.ok) {
const fallback = (await zhLandscape.json()) as PrebakedFirstAct;
return { ...fallback, scene: { ...fallback.scene, orientation: "landscape" as const } };
}
}
}
throw new Error(t("home.errors.cardNotFound", { cardName }));
},
@@ -2465,7 +2482,7 @@ function PlayInner() {
{error}
</p>
<Link
href="/"
href={lp("/")}
className="mt-4 text-[10px] smallcaps text-clay-700 hover:text-ember-500 transition-colors inline-flex items-center gap-3"
>
<i className="fa-solid fa-arrow-left text-[9px]" />
@@ -2512,7 +2529,7 @@ function PlayInner() {
style={{ paddingTop: "max(0.5rem, env(safe-area-inset-top))" }}
>
<Link
href="/"
href={lp("/")}
className="pointer-events-auto flex h-9 w-9 items-center justify-center rounded-full bg-black/40 text-white/80 backdrop-blur-sm transition-colors hover:text-white"
aria-label={t("play.tooltips.back")}
>
@@ -2590,7 +2607,7 @@ function PlayInner() {
)}
<header className="px-5 md:px-12 pt-6 md:pt-8 flex items-center justify-between">
<Link
href="/"
href={lp("/")}
className="text-clay-600 hover:text-clay-900 transition-colors flex items-center gap-3"
>
<i className="fa-solid fa-arrow-left text-[12px]" />
@@ -1,16 +1,27 @@
import type { Metadata } from "next";
import Link from "next/link";
import { localePath } from "@/lib/i18n/navigation";
import { isValidLocale } from "@/lib/i18n/utils";
import { DEFAULT_LOCALE, type Locale } from "@/lib/i18n/config";
export const metadata: Metadata = {
title: "隐私政策 — InfiPlot",
description: "InfiPlot 隐私政策:了解我们如何收集、使用和保护您的个人信息。",
};
export default function PrivacyPage() {
export default async function PrivacyPage({
params,
}: {
params: Promise<{ locale: string }>;
}) {
const { locale: rawLocale } = await params;
const locale: Locale = isValidLocale(rawLocale) ? rawLocale : DEFAULT_LOCALE;
const lp = (path: string) => localePath(path, locale);
return (
<main className="mx-auto w-full max-w-3xl px-6 md:px-16 py-16 md:py-24">
<Link
href="/"
href={lp("/")}
className="inline-flex items-center gap-2 text-clay-500 hover:text-ember-500 transition-colors text-sm mb-12"
>
<i className="fa-solid fa-arrow-left text-xs" />
@@ -4,8 +4,10 @@ import Link from "next/link";
import { useEffect, useState } from "react";
import { loadStoryList, deleteStory } from "@/lib/clientStoryPersistence";
import type { StoryMeta } from "@/lib/db/repositories/storyRepo";
import { useLocalePath } from "@/lib/i18n/hooks";
export default function StoriesPage() {
const lp = useLocalePath();
const [stories, setStories] = useState<StoryMeta[]>([]);
const [loading, setLoading] = useState(true);
const [deletingId, setDeletingId] = useState<string | null>(null);
@@ -58,7 +60,7 @@ export default function StoriesPage() {
{/* ================== HEADER ================== */}
<header className="px-6 md:px-16 pt-7 md:pt-10 flex items-center justify-between">
<Link
href="/"
href={lp("/")}
className="text-[10px] smallcaps text-clay-700 hover:text-clay-900 transition-colors flex items-center gap-2 cursor-pointer"
>
<i className="fa-solid fa-arrow-left text-[9px]" />
@@ -84,7 +86,7 @@ export default function StoriesPage() {
</p>
<Link
href="/"
href={lp("/")}
className="text-[10px] smallcaps text-clay-700 hover:text-ember-500 transition-colors cursor-pointer"
>
@@ -99,7 +101,7 @@ export default function StoriesPage() {
className="bg-cream-100 border border-clay-900/10 rounded-sm p-6 transition-all duration-200 hover:shadow-md hover:border-clay-900/20 relative group"
>
<Link
href={`/play?storyId=${encodeURIComponent(story.id)}`}
href={lp(`/play?storyId=${encodeURIComponent(story.id)}`)}
className="block cursor-pointer"
>
<div className="mb-4">
@@ -1,16 +1,27 @@
import type { Metadata } from "next";
import Link from "next/link";
import { localePath } from "@/lib/i18n/navigation";
import { isValidLocale } from "@/lib/i18n/utils";
import { DEFAULT_LOCALE, type Locale } from "@/lib/i18n/config";
export const metadata: Metadata = {
title: "服务条款 — InfiPlot",
description: "InfiPlot 服务条款:使用 InfiPlot 服务前请阅读本条款。",
};
export default function TermsPage() {
export default async function TermsPage({
params,
}: {
params: Promise<{ locale: string }>;
}) {
const { locale: rawLocale } = await params;
const locale: Locale = isValidLocale(rawLocale) ? rawLocale : DEFAULT_LOCALE;
const lp = (path: string) => localePath(path, locale);
return (
<main className="mx-auto w-full max-w-3xl px-6 md:px-16 py-16 md:py-24">
<Link
href="/"
href={lp("/")}
className="inline-flex items-center gap-2 text-clay-500 hover:text-ember-500 transition-colors text-sm mb-12"
>
<i className="fa-solid fa-arrow-left text-xs" />
@@ -124,7 +135,7 @@ export default function TermsPage() {
<p>
AI {" "}
<Link
href="/privacy"
href={lp("/privacy")}
className="text-ember-500 hover:text-ember-400 transition-colors underline decoration-clay-900/20 underline-offset-2"
>
+27 -4
View File
@@ -1,7 +1,10 @@
import type { Metadata, Viewport } from "next";
import { headers } from "next/headers";
import { Cormorant_Garamond, Inter } from "next/font/google";
import { Analytics } from "@/components/Analytics";
import { I18nProvider } from "@/lib/i18n/client";
import { LOCALES, DEFAULT_LOCALE, type Locale } from "@/lib/i18n/config";
import { localePath } from "@/lib/i18n/navigation";
import { stripLocalePrefix } from "@/lib/i18n/navigation";
import "./globals.css";
// Editorial fonts: drive tailwind `font-serif`/`font-sans` via
@@ -35,14 +38,25 @@ export const viewport: Viewport = {
viewportFit: "cover",
};
export default function RootLayout({
export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const headersList = await headers();
const locale = headersList.get("x-locale") || "zh-CN";
const origin =
process.env.NEXT_PUBLIC_BASE_URL
|| (process.env.VERCEL_PROJECT_PRODUCTION_URL
? `https://${process.env.VERCEL_PROJECT_PRODUCTION_URL}`
: "https://infiplot.com");
const pathname = headersList.get("x-pathname") || "/";
const barePath = stripLocalePrefix(pathname);
return (
<html
lang="zh-CN"
lang={locale}
className={`${cormorant.variable} ${inter.variable}`}
suppressHydrationWarning
>
@@ -52,9 +66,18 @@ export default function RootLayout({
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
/>
{LOCALES.map((l) => (
<link
key={l}
rel="alternate"
hrefLang={l}
href={`${origin}${localePath(barePath, l)}`}
/>
))}
<link rel="alternate" hrefLang="x-default" href={`${origin}${barePath}`} />
</head>
<body className="bg-cream-50 text-clay-900 font-sans antialiased min-h-screen overflow-x-hidden">
<I18nProvider>{children}</I18nProvider>
{children}
<Analytics />
</body>
</html>