index.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 } 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. const LANG_KEY = "lang";
  33. const DEFAULT_LANG = "en";
  34. function getItem(key: string) {
  35. try {
  36. return localStorage.getItem(key);
  37. } catch {
  38. return null;
  39. }
  40. }
  41. function setItem(key: string, value: string) {
  42. try {
  43. localStorage.setItem(key, value);
  44. } catch {}
  45. }
  46. function getLanguage() {
  47. try {
  48. return navigator.language.toLowerCase();
  49. } catch {
  50. console.log("[Lang] failed to detect user lang.");
  51. return DEFAULT_LANG;
  52. }
  53. }
  54. export function getLang(): Lang {
  55. const savedLang = getItem(LANG_KEY);
  56. if (AllLangs.includes((savedLang ?? "") as Lang)) {
  57. return savedLang as Lang;
  58. }
  59. const lang = getLanguage();
  60. for (const option of AllLangs) {
  61. if (lang.includes(option)) {
  62. return option;
  63. }
  64. }
  65. return DEFAULT_LANG;
  66. }
  67. export function changeLang(lang: Lang) {
  68. setItem(LANG_KEY, lang);
  69. location.reload();
  70. }
  71. const fallbackLang = EN;
  72. const targetLang = {
  73. en: EN,
  74. cn: CN,
  75. tw: TW,
  76. fr: FR,
  77. es: ES,
  78. it: IT,
  79. tr: TR,
  80. jp: JP,
  81. de: DE,
  82. vi: VI,
  83. ru: RU,
  84. cs: CS,
  85. ko: KO,
  86. }[getLang()] as typeof CN;
  87. // if target lang missing some fields, it will use fallback lang string
  88. merge(fallbackLang, targetLang);
  89. export default fallbackLang as typeof CN;