index.ts 2.1 KB

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