mirror of
https://gitee.com/wanwujie/deer-flow
synced 2026-04-27 15:54:48 +08:00
feat: save locale in cookies
This commit is contained in:
@@ -1,7 +1,9 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
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";
|
||||
|
||||
@@ -13,41 +15,24 @@ const translations: Record<Locale, Translations> = {
|
||||
};
|
||||
|
||||
export function useI18n() {
|
||||
const [locale, setLocale] = useState<Locale>(() => {
|
||||
if (typeof window === "undefined") {
|
||||
return "en-US";
|
||||
}
|
||||
|
||||
// Try to get from localStorage first
|
||||
const saved = localStorage.getItem("locale") as Locale | null;
|
||||
if (saved && (saved === "en-US" || saved === "zh-CN")) {
|
||||
return saved;
|
||||
}
|
||||
|
||||
// Otherwise detect from browser
|
||||
return detectLocale();
|
||||
});
|
||||
const { locale, setLocale } = useI18nContext();
|
||||
|
||||
const t = translations[locale];
|
||||
|
||||
const changeLocale = (newLocale: Locale) => {
|
||||
setLocale(newLocale);
|
||||
if (typeof window !== "undefined") {
|
||||
localStorage.setItem("locale", newLocale);
|
||||
}
|
||||
setLocaleInCookie(newLocale);
|
||||
};
|
||||
|
||||
// Initialize locale on mount
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined") {
|
||||
const saved = localStorage.getItem("locale") as Locale | null;
|
||||
if (!saved) {
|
||||
const detected = detectLocale();
|
||||
setLocale(detected);
|
||||
localStorage.setItem("locale", detected);
|
||||
}
|
||||
const saved = getLocaleFromCookie() as Locale | null;
|
||||
if (!saved) {
|
||||
const detected = detectLocale();
|
||||
setLocale(detected);
|
||||
setLocaleInCookie(detected);
|
||||
}
|
||||
}, []);
|
||||
}, [setLocale]);
|
||||
|
||||
return {
|
||||
locale,
|
||||
|
||||
Reference in New Issue
Block a user