|
| 1 | +"use client"; |
| 2 | + |
| 3 | +/** |
| 4 | + * Header 里的语言切换按钮(匿名也能用)。 |
| 5 | + * |
| 6 | + * 为什么要做: |
| 7 | + * 之前切语言的唯一入口在 /settings 页面,UserMenu 里只有登录用户能看到。 |
| 8 | + * 访客看到的永远是默认 zh,站点对英语用户非常不友好。 |
| 9 | + * |
| 10 | + * 实现: |
| 11 | + * - 写 locale=zh|en 到 document.cookie(path=/,一年有效期,samesite=lax) |
| 12 | + * 字段和格式与 SettingsForm 完全一致,登录用户在设置页改的偏好仍然生效 |
| 13 | + * - 切完 router.refresh() 让 SSR 重新渲染,server component(Hero / docs |
| 14 | + * 详情页等)从 cookie 读新 locale 切文案 |
| 15 | + * - 简单的 ZH / EN 双字母展示,当前语言高亮;button 尺寸与 ThemeToggle 对齐 |
| 16 | + */ |
| 17 | + |
| 18 | +import { useEffect, useState } from "react"; |
| 19 | +import { useRouter } from "next/navigation"; |
| 20 | +import { Button } from "@/components/ui/button"; |
| 21 | + |
| 22 | +type Locale = "zh" | "en"; |
| 23 | + |
| 24 | +function readLocaleCookie(): Locale { |
| 25 | + if (typeof document === "undefined") return "zh"; |
| 26 | + const m = document.cookie.match(/(?:^|;\s*)locale=([^;]+)/); |
| 27 | + const v = m?.[1]; |
| 28 | + return v === "en" ? "en" : "zh"; |
| 29 | +} |
| 30 | + |
| 31 | +function writeLocaleCookie(next: Locale) { |
| 32 | + // 一年;samesite=lax 够用(这个 cookie 不涉及跨站 POST) |
| 33 | + document.cookie = `locale=${next};path=/;max-age=${60 * 60 * 24 * 365};samesite=lax`; |
| 34 | +} |
| 35 | + |
| 36 | +export function LocaleToggle() { |
| 37 | + const router = useRouter(); |
| 38 | + // 初始 render 先给默认值避免 hydration 不一致,真实值由 useEffect 读 cookie 后覆盖 |
| 39 | + const [locale, setLocale] = useState<Locale>("zh"); |
| 40 | + const [ready, setReady] = useState(false); |
| 41 | + |
| 42 | + useEffect(() => { |
| 43 | + setLocale(readLocaleCookie()); |
| 44 | + setReady(true); |
| 45 | + }, []); |
| 46 | + |
| 47 | + const toggle = () => { |
| 48 | + const next: Locale = locale === "zh" ? "en" : "zh"; |
| 49 | + writeLocaleCookie(next); |
| 50 | + setLocale(next); |
| 51 | + // 刷新 server component 树,重新按 cookie 渲染各页面 |
| 52 | + router.refresh(); |
| 53 | + }; |
| 54 | + |
| 55 | + return ( |
| 56 | + <Button |
| 57 | + variant="ghost" |
| 58 | + size="sm" |
| 59 | + onClick={toggle} |
| 60 | + aria-label="Toggle language" |
| 61 | + title={locale === "zh" ? "切换为 English" : "Switch to 中文"} |
| 62 | + className="h-10 px-2 rounded-none font-mono text-xs uppercase tracking-widest transition-colors" |
| 63 | + data-umami-event="locale_toggle" |
| 64 | + data-umami-event-locale={locale === "zh" ? "en" : "zh"} |
| 65 | + > |
| 66 | + <span className={ready && locale === "zh" ? "font-bold" : "opacity-50"}> |
| 67 | + ZH |
| 68 | + </span> |
| 69 | + <span className="opacity-30 mx-0.5">/</span> |
| 70 | + <span className={ready && locale === "en" ? "font-bold" : "opacity-50"}> |
| 71 | + EN |
| 72 | + </span> |
| 73 | + </Button> |
| 74 | + ); |
| 75 | +} |
0 commit comments