Add language switcher dropdown and persist manual locale choice.
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -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 (
|
||||
|
||||
Reference in New Issue
Block a user