ChatGPT-Next-Web/app/locales/index.ts

86 lines
1.4 KiB
TypeScript
Raw Normal View History

2023-03-28 17:39:14 +00:00
import CN from "./cn";
import EN from "./en";
import TW from "./tw";
2023-03-31 00:48:57 +00:00
import ES from "./es";
2023-04-02 17:23:50 +00:00
import IT from "./it";
2023-04-10 09:04:30 +00:00
import TR from "./tr";
2023-04-10 14:01:54 +00:00
import JP from "./jp";
2023-04-16 05:07:54 +00:00
import DE from "./de";
2023-05-07 07:54:09 +00:00
import VI from "./vi";
2023-03-20 16:17:45 +00:00
2023-03-28 17:39:14 +00:00
export type { LocaleType } from "./cn";
2023-03-20 16:17:45 +00:00
2023-04-16 05:07:54 +00:00
export const AllLangs = [
"en",
"cn",
"tw",
"es",
"it",
"tr",
"jp",
"de",
2023-05-07 07:54:09 +00:00
"vi",
2023-04-16 05:07:54 +00:00
] as const;
2023-04-23 17:15:44 +00:00
export type Lang = (typeof AllLangs)[number];
2023-03-20 16:17:45 +00:00
2023-03-28 17:39:14 +00:00
const LANG_KEY = "lang";
2023-05-03 07:22:44 +00:00
const DEFAULT_LANG = "en";
2023-03-20 16:25:27 +00:00
function getItem(key: string) {
2023-03-28 17:39:14 +00:00
try {
return localStorage.getItem(key);
} catch {
return null;
}
2023-03-20 16:25:27 +00:00
}
function setItem(key: string, value: string) {
2023-03-28 17:39:14 +00:00
try {
localStorage.setItem(key, value);
} catch {}
2023-03-20 16:25:27 +00:00
}
function getLanguage() {
2023-03-28 17:39:14 +00:00
try {
return navigator.language.toLowerCase();
} catch {
2023-05-03 07:22:44 +00:00
console.log("[Lang] failed to detect user lang.");
return DEFAULT_LANG;
2023-03-28 17:39:14 +00:00
}
2023-03-20 16:25:27 +00:00
}
2023-03-20 16:17:45 +00:00
export function getLang(): Lang {
2023-03-28 17:39:14 +00:00
const savedLang = getItem(LANG_KEY);
2023-03-20 16:17:45 +00:00
2023-03-28 17:39:14 +00:00
if (AllLangs.includes((savedLang ?? "") as Lang)) {
return savedLang as Lang;
}
2023-03-20 16:17:45 +00:00
2023-03-28 17:39:14 +00:00
const lang = getLanguage();
2023-03-20 16:17:45 +00:00
for (const option of AllLangs) {
if (lang.includes(option)) {
return option;
}
2023-03-28 17:39:14 +00:00
}
2023-05-03 07:22:44 +00:00
return DEFAULT_LANG;
2023-03-20 16:17:45 +00:00
}
export function changeLang(lang: Lang) {
2023-03-28 17:39:14 +00:00
setItem(LANG_KEY, lang);
location.reload();
2023-03-20 16:17:45 +00:00
}
2023-04-16 05:07:54 +00:00
export default {
en: EN,
cn: CN,
tw: TW,
es: ES,
it: IT,
tr: TR,
jp: JP,
de: DE,
2023-05-07 07:54:09 +00:00
vi: VI,
}[getLang()] as typeof CN;