index.ts 2.0 KB

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