index.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  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 ar from "./ar";
  16. import bn from "./bn";
  17. import { merge } from "../utils/merge";
  18. import type { LocaleType } from "./cn";
  19. export type { LocaleType, PartialLocaleType } from "./cn";
  20. const ALL_LANGS = {
  21. cn,
  22. en,
  23. tw,
  24. jp,
  25. ko,
  26. fr,
  27. es,
  28. it,
  29. tr,
  30. de,
  31. vi,
  32. ru,
  33. cs,
  34. no,
  35. ar,
  36. bn,
  37. };
  38. export type Lang = keyof typeof ALL_LANGS;
  39. export const AllLangs = Object.keys(ALL_LANGS) as Lang[];
  40. export const ALL_LANG_OPTIONS: Record<Lang, string> = {
  41. cn: "简体中文",
  42. en: "English",
  43. tw: "繁體中文",
  44. jp: "日本語",
  45. ko: "한국어",
  46. fr: "Français",
  47. es: "Español",
  48. it: "Italiano",
  49. tr: "Türkçe",
  50. de: "Deutsch",
  51. vi: "Tiếng Việt",
  52. ru: "Русский",
  53. cs: "Čeština",
  54. no: "Nynorsk",
  55. ar: "العربية",
  56. bn: "বাংলা",
  57. };
  58. const LANG_KEY = "lang";
  59. const DEFAULT_LANG = "en";
  60. const fallbackLang = en;
  61. const targetLang = ALL_LANGS[getLang()] as LocaleType;
  62. // if target lang missing some fields, it will use fallback lang string
  63. merge(fallbackLang, targetLang);
  64. export default fallbackLang as LocaleType;
  65. function getItem(key: string) {
  66. try {
  67. return localStorage.getItem(key);
  68. } catch {
  69. return null;
  70. }
  71. }
  72. function setItem(key: string, value: string) {
  73. try {
  74. localStorage.setItem(key, value);
  75. } catch {}
  76. }
  77. function getLanguage() {
  78. try {
  79. return navigator.language.toLowerCase();
  80. } catch {
  81. return DEFAULT_LANG;
  82. }
  83. }
  84. export function getLang(): Lang {
  85. const savedLang = getItem(LANG_KEY);
  86. if (AllLangs.includes((savedLang ?? "") as Lang)) {
  87. return savedLang as Lang;
  88. }
  89. const lang = getLanguage();
  90. for (const option of AllLangs) {
  91. if (lang.includes(option)) {
  92. return option;
  93. }
  94. }
  95. return DEFAULT_LANG;
  96. }
  97. export function changeLang(lang: Lang) {
  98. setItem(LANG_KEY, lang);
  99. location.reload();
  100. }