index.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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 NO from "./no";
  13. import CS from "./cs";
  14. import KO from "./ko";
  15. import { merge } from "../utils/merge";
  16. export type { LocaleType, RequiredLocaleType } from "./cn";
  17. export const AllLangs = [
  18. "en",
  19. "cn",
  20. "tw",
  21. "fr",
  22. "es",
  23. "it",
  24. "tr",
  25. "jp",
  26. "de",
  27. "vi",
  28. "ru",
  29. "cs",
  30. "ko",
  31. ] as const;
  32. export type Lang = (typeof AllLangs)[number];
  33. export const ALL_LANG_OPTIONS: Record<Lang, string> = {
  34. cn: "简体中文",
  35. en: "English",
  36. tw: "繁體中文",
  37. fr: "Français",
  38. es: "Español",
  39. it: "Italiano",
  40. tr: "Türkçe",
  41. jp: "日本語",
  42. de: "Deutsch",
  43. vi: "Tiếng Việt",
  44. ru: "Русский",
  45. cs: "Čeština",
  46. ko: "한국어",
  47. };
  48. const LANG_KEY = "lang";
  49. const DEFAULT_LANG = "en";
  50. function getItem(key: string) {
  51. try {
  52. return localStorage.getItem(key);
  53. } catch {
  54. return null;
  55. }
  56. }
  57. function setItem(key: string, value: string) {
  58. try {
  59. localStorage.setItem(key, value);
  60. } catch {}
  61. }
  62. function getLanguage() {
  63. try {
  64. return navigator.language.toLowerCase();
  65. } catch {
  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. no: NO,
  100. cs: CS,
  101. ko: KO,
  102. }[getLang()] as typeof CN;
  103. // if target lang missing some fields, it will use fallback lang string
  104. merge(fallbackLang, targetLang);
  105. export default fallbackLang as typeof CN;