index.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. import CN from "./cn";
  2. import EN from "./en";
  3. import TW from "./tw";
  4. import FR from "./fr";
  5. import ES from "./es";
  6. import IT from "./it";
  7. import TR from "./tr";
  8. import JP from "./jp";
  9. import DE from "./de";
  10. import VI from "./vi";
  11. import RU from "./ru";
  12. import CS from "./cs";
  13. import KO from "./ko";
  14. import { merge } from "../utils/merge";
  15. export type { LocaleType, RequiredLocaleType } from "./cn";
  16. export const AllLangs = [
  17. "en",
  18. "cn",
  19. "tw",
  20. "fr",
  21. "es",
  22. "it",
  23. "tr",
  24. "jp",
  25. "de",
  26. "vi",
  27. "ru",
  28. "cs",
  29. "ko",
  30. ] as const;
  31. export type Lang = (typeof AllLangs)[number];
  32. export const ALL_LANG_OPTIONS: Record<Lang, string> = {
  33. cn: "简体中文",
  34. en: "English",
  35. tw: "繁體中文",
  36. fr: "Français",
  37. es: "Español",
  38. it: "Italiano",
  39. tr: "Türkçe",
  40. jp: "日本語",
  41. de: "Deutsch",
  42. vi: "Tiếng Việt",
  43. ru: "Русский",
  44. cs: "Čeština",
  45. ko: "한국어",
  46. };
  47. const LANG_KEY = "lang";
  48. const DEFAULT_LANG = "en";
  49. function getItem(key: string) {
  50. try {
  51. return localStorage.getItem(key);
  52. } catch {
  53. return null;
  54. }
  55. }
  56. function setItem(key: string, value: string) {
  57. try {
  58. localStorage.setItem(key, value);
  59. } catch {}
  60. }
  61. function getLanguage() {
  62. try {
  63. return navigator.language.toLowerCase();
  64. } catch {
  65. console.log("[Lang] failed to detect user lang.");
  66. return DEFAULT_LANG;
  67. }
  68. }
  69. export function getLang(): Lang {
  70. const savedLang = getItem(LANG_KEY);
  71. if (AllLangs.includes((savedLang ?? "") as Lang)) {
  72. return savedLang as Lang;
  73. }
  74. const lang = getLanguage();
  75. for (const option of AllLangs) {
  76. if (lang.includes(option)) {
  77. return option;
  78. }
  79. }
  80. return DEFAULT_LANG;
  81. }
  82. export function changeLang(lang: Lang) {
  83. setItem(LANG_KEY, lang);
  84. location.reload();
  85. }
  86. const fallbackLang = EN;
  87. const targetLang = {
  88. en: EN,
  89. cn: CN,
  90. tw: TW,
  91. fr: FR,
  92. es: ES,
  93. it: IT,
  94. tr: TR,
  95. jp: JP,
  96. de: DE,
  97. vi: VI,
  98. ru: RU,
  99. cs: CS,
  100. ko: KO,
  101. }[getLang()] as typeof CN;
  102. // if target lang missing some fields, it will use fallback lang string
  103. merge(fallbackLang, targetLang);
  104. export default fallbackLang as typeof CN;