Hide the language switcher for English-only browsers; gate /zh via Accept-Language and a client cookie. Co-authored-by: Cursor <cursoragent@cursor.com>
72 lines
2.0 KiB
TypeScript
72 lines
2.0 KiB
TypeScript
"use client";
|
|
|
|
import { useEffect, useMemo, useState } from "react";
|
|
import { useLocale, useTranslations } from "next-intl";
|
|
import { usePathname, useRouter } from "@/i18n/navigation";
|
|
import type { AppLocale } from "@/i18n/routing";
|
|
import {
|
|
detectChineseClient,
|
|
markChineseLocaleAllowed,
|
|
} from "@/lib/chinese-locale";
|
|
import { cn } from "@/lib/utils";
|
|
|
|
export function LanguageSwitcher() {
|
|
const t = useTranslations("lang");
|
|
const locale = useLocale() as AppLocale;
|
|
const router = useRouter();
|
|
const pathname = usePathname();
|
|
const [ready, setReady] = useState(false);
|
|
const [zhAvailable, setZhAvailable] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const { likely } = detectChineseClient();
|
|
setZhAvailable(likely);
|
|
setReady(true);
|
|
|
|
if (likely) {
|
|
markChineseLocaleAllowed();
|
|
} else if (locale === "zh") {
|
|
router.replace(pathname, { locale: "en" });
|
|
}
|
|
}, [locale, pathname, router]);
|
|
|
|
const locales = useMemo(() => {
|
|
const list: AppLocale[] = ["en"];
|
|
if (zhAvailable) list.push("zh");
|
|
return list;
|
|
}, [zhAvailable]);
|
|
|
|
// English-only environments: no language control
|
|
if (!ready || locales.length < 2) {
|
|
return null;
|
|
}
|
|
|
|
return (
|
|
<div
|
|
className="inline-flex items-center gap-1 rounded-lg border border-[var(--line)] p-0.5"
|
|
role="group"
|
|
aria-label={t("label")}
|
|
>
|
|
{locales.map((loc) => (
|
|
<button
|
|
key={loc}
|
|
type="button"
|
|
className={cn(
|
|
"rounded-md px-2.5 py-1 text-xs font-medium transition-colors",
|
|
loc === locale
|
|
? "bg-[rgba(240,197,10,0.18)] text-[var(--accent-hot)]"
|
|
: "text-[var(--muted)] hover:text-[var(--ink)]"
|
|
)}
|
|
aria-pressed={loc === locale}
|
|
onClick={() => {
|
|
if (loc === "zh") markChineseLocaleAllowed();
|
|
router.replace(pathname, { locale: loc });
|
|
}}
|
|
>
|
|
{t(loc)}
|
|
</button>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|