Files
deer-flow/frontend/src/core/i18n/hooks.ts
T
Xinmin Zeng e9adaab7a6 fix(i18n): normalize locale and prevent undefined translations (#914)
* fix(i18n): guard locale input and add safe translation fallback

* refactor(i18n): isolate locale utils and normalize server cookie decode

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
2026-02-27 08:10:38 +08:00

56 lines
1.2 KiB
TypeScript

"use client";
import { useEffect } from "react";
import { useI18nContext } from "./context";
import { getLocaleFromCookie, setLocaleInCookie } from "./cookies";
import { enUS } from "./locales/en-US";
import { zhCN } from "./locales/zh-CN";
import {
DEFAULT_LOCALE,
detectLocale,
normalizeLocale,
type Locale,
type Translations,
} from "./index";
const translations: Record<Locale, Translations> = {
"en-US": enUS,
"zh-CN": zhCN,
};
export function useI18n() {
const { locale, setLocale } = useI18nContext();
const t = translations[locale] ?? translations[DEFAULT_LOCALE];
const changeLocale = (newLocale: Locale) => {
setLocale(newLocale);
setLocaleInCookie(newLocale);
};
// Initialize locale on mount
useEffect(() => {
const saved = getLocaleFromCookie();
if (saved) {
const normalizedSaved = normalizeLocale(saved);
setLocale(normalizedSaved);
if (saved !== normalizedSaved) {
setLocaleInCookie(normalizedSaved);
}
return;
}
const detected = detectLocale();
setLocale(detected);
setLocaleInCookie(detected);
}, [setLocale]);
return {
locale,
t,
changeLocale,
};
}