Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions app/components/Header.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { ThemeToggle } from "./ThemeToggle";
import { LocaleToggle } from "./LocaleToggle";
import { Button } from "@/components/ui/button";
import { MessageCircle } from "lucide-react";
import { Github as GithubIcon } from "./icons/Github";
Expand Down Expand Up @@ -106,6 +107,7 @@ export async function Header() {
<MessageCircle className="h-4 w-4" />
</a>
</Button>
<LocaleToggle />
<ThemeToggle />
<AuthNav />
</div>
Expand Down
85 changes: 85 additions & 0 deletions app/components/LocaleToggle.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
"use client";

/**
* Header 里的语言切换按钮(匿名也能用)。
*
* 为什么要做:
* 之前切语言的唯一入口在 /settings 页面,UserMenu 里只有登录用户能看到。
* 访客看到的永远是默认 zh,站点对英语用户非常不友好。
*
* 实现:
* - 写 locale=zh|en 到 document.cookie(path=/,一年有效期,samesite=lax)
* 字段和格式与 SettingsForm 完全一致,登录用户在设置页改的偏好仍然生效
* - 切完 router.refresh() 让 SSR 重新渲染,server component(Hero / docs
* 详情页等)从 cookie 读新 locale 切文案
* - 简单的 ZH / EN 双字母展示,当前语言高亮;button 尺寸与 ThemeToggle 对齐
*
* 不做的事:
* - 不读后端 user_preferences:游客无账号,登录用户在 /settings 改完也只是
* 写同一条 cookie,这里读 cookie 即可统一视图。
* - 不做 URL prefix 切换(/zh/xxx、/en/xxx):站点当前没有 i18n 路由分段,
* 硬改会牵动大量路由和 sitemap。Cookie 方案延续现状,后续若要 SEO 双语
* URL 再另开 PR。
*/

import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "../../components/ui/button";

type Locale = "zh" | "en";

function readLocaleCookie(): Locale {
if (typeof document === "undefined") return "zh";
const m = document.cookie.match(/(?:^|;\s*)locale=([^;]+)/);
const v = m?.[1];
return v === "en" ? "en" : "zh";
}

function writeLocaleCookie(next: Locale) {
// 一年;samesite=lax 够用(这个 cookie 不涉及跨站 POST)
document.cookie = `locale=${next};path=/;max-age=${60 * 60 * 24 * 365};samesite=lax`;
}

export function LocaleToggle() {
const router = useRouter();
// 初始 render 先给默认值,避免 SSR 和 CSR 结构不同触发 hydration 警告;
// 真实值由 useEffect 读 cookie 后再覆盖
const [locale, setLocale] = useState<Locale>("zh");
Comment on lines +31 to +47
Copy link

Copilot AI Apr 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这里的 locale cookie 读取/写入逻辑(正则、默认值、max-age / samesite 等)与 app/settings/SettingsForm.tsx 重复;两处都宣称“格式完全一致”,后续任一处改动容易产生 drift。建议抽到一个共享 helper(如 lib/locale-cookie.ts),由 SettingsForm / LocaleToggle 共同复用。

Suggested change
function readLocaleCookie(): Locale {
if (typeof document === "undefined") return "zh";
const m = document.cookie.match(/(?:^|;\s*)locale=([^;]+)/);
const v = m?.[1];
return v === "en" ? "en" : "zh";
}
function writeLocaleCookie(next: Locale) {
// 一年;samesite=lax 够用(这个 cookie 不涉及跨站 POST)
document.cookie = `locale=${next};path=/;max-age=${60 * 60 * 24 * 365};samesite=lax`;
}
export function LocaleToggle() {
const router = useRouter();
// 初始 render 先给默认值,避免 SSR 和 CSR 结构不同触发 hydration 警告;
// 真实值由 useEffect 读 cookie 后再覆盖
const [locale, setLocale] = useState<Locale>("zh");
const DEFAULT_LOCALE: Locale = "zh";
const LOCALE_COOKIE_NAME = "locale";
const LOCALE_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
const LOCALE_COOKIE_PATTERN = new RegExp(
`(?:^|;\\s*)${LOCALE_COOKIE_NAME}=([^;]+)`,
);
function normalizeLocale(value?: string): Locale {
return value === "en" ? "en" : DEFAULT_LOCALE;
}
function buildLocaleCookie(next: Locale): string {
// 一年;samesite=lax 够用(这个 cookie 不涉及跨站 POST)
return `${LOCALE_COOKIE_NAME}=${next};path=/;max-age=${LOCALE_COOKIE_MAX_AGE};samesite=lax`;
}
function readLocaleCookie(): Locale {
if (typeof document === "undefined") return DEFAULT_LOCALE;
const m = document.cookie.match(LOCALE_COOKIE_PATTERN);
return normalizeLocale(m?.[1]);
}
function writeLocaleCookie(next: Locale) {
document.cookie = buildLocaleCookie(next);
}
export function LocaleToggle() {
const router = useRouter();
// 初始 render 先给默认值,避免 SSR 和 CSR 结构不同触发 hydration 警告;
// 真实值由 useEffect 读 cookie 后再覆盖
const [locale, setLocale] = useState<Locale>(DEFAULT_LOCALE);

Copilot uses AI. Check for mistakes.
const [ready, setReady] = useState(false);

useEffect(() => {
setLocale(readLocaleCookie());
setReady(true);
}, []);

const toggle = () => {
const next: Locale = locale === "zh" ? "en" : "zh";
writeLocaleCookie(next);
setLocale(next);
if (typeof window !== "undefined" && window.umami) {
window.umami.track("locale_toggle", { locale: next });
}
// 刷新 server component 树,重新按 cookie 渲染各页面
router.refresh();
};

return (
<Button
variant="ghost"
size="sm"
onClick={toggle}
aria-label="Toggle language"
title={locale === "zh" ? "切换为 English" : "Switch to 中文"}
Comment on lines +66 to +72
Copy link

Copilot AI Apr 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

title 文案在首屏会基于默认 state(zh)渲染;如果用户 cookie 实际是 en,水合前的 tooltip 会短暂显示为“切换为 English”。可以在 ready === false 时使用中性 title(如 "Toggle language"),或把 title 文案也用 ready/cookie 读到后再切换,避免误导。

Suggested change
return (
<Button
variant="ghost"
size="sm"
onClick={toggle}
aria-label="Toggle language"
title={locale === "zh" ? "切换为 English" : "Switch to 中文"}
const title = !ready
? "Toggle language"
: locale === "zh"
? "切换为 English"
: "Switch to 中文";
return (
<Button
variant="ghost"
size="sm"
onClick={toggle}
aria-label="Toggle language"
title={title}

Copilot uses AI. Check for mistakes.
className="h-10 px-2 rounded-none font-mono text-xs uppercase tracking-widest transition-colors"
>
{/* 未 hydrate 时默认展示 ZH/EN 两字,hydrate 后根据 cookie 高亮当前 */}
<span className={ready && locale === "zh" ? "font-bold" : "opacity-50"}>
ZH
</span>
<span className="opacity-30 mx-0.5">/</span>
<span className={ready && locale === "en" ? "font-bold" : "opacity-50"}>
EN
</span>
</Button>
);
}
Loading