Add language switcher dropdown and persist manual locale choice.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric
2026-08-03 09:02:19 -05:00
parent af0a430864
commit 7453780e06
6 changed files with 96 additions and 7 deletions

View File

@@ -2,6 +2,7 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
@@ -11,32 +12,47 @@ import {
import { isChinaUser } from "is-china-user";
import { dictionaries, type Dictionary, type Locale } from "~/lib/i18n";
const STORAGE_KEY = "nomadro-locale";
type LocaleContextValue = {
locale: Locale;
isChina: boolean;
ready: boolean;
t: Dictionary;
setLocale: (locale: Locale) => void;
};
const LocaleContext = createContext<LocaleContextValue | null>(null);
function isLocale(value: string | null): value is Locale {
return value === "zh" || value === "en";
}
export function LocaleProvider({ children }: { children: ReactNode }) {
// Default zh to match primary audience; switch after client detection.
const [locale, setLocale] = useState<Locale>("zh");
const [locale, setLocaleState] = useState<Locale>("zh");
const [ready, setReady] = useState(false);
useEffect(() => {
let cancelled = false;
try {
const saved = window.localStorage.getItem(STORAGE_KEY);
if (isLocale(saved)) {
if (!cancelled) {
setLocaleState(saved);
setReady(true);
}
return;
}
const china = Boolean(isChinaUser());
if (!cancelled) {
setLocale(china ? "zh" : "en");
setLocaleState(china ? "zh" : "en");
setReady(true);
}
} catch {
if (!cancelled) {
setLocale("zh");
setLocaleState("zh");
setReady(true);
}
}
@@ -51,14 +67,24 @@ export function LocaleProvider({ children }: { children: ReactNode }) {
document.documentElement.lang = dictionaries[locale].htmlLang;
}, [locale, ready]);
const setLocale = useCallback((next: Locale) => {
setLocaleState(next);
try {
window.localStorage.setItem(STORAGE_KEY, next);
} catch {
// ignore storage failures
}
}, []);
const value = useMemo<LocaleContextValue>(
() => ({
locale,
isChina: locale === "zh",
ready,
t: dictionaries[locale],
setLocale,
}),
[locale, ready],
[locale, ready, setLocale],
);
return (