index.ts 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. export type { LocaleType } from "./cn";
  14. export const AllLangs = [
  15. "en",
  16. "cn",
  17. "tw",
  18. "fr",
  19. "es",
  20. "it",
  21. "tr",
  22. "jp",
  23. "de",
  24. "vi",
  25. "ru",
  26. "cs",
  27. ] as const;
  28. export type Lang = (typeof AllLangs)[number];
  29. const LANG_KEY = "lang";
  30. const DEFAULT_LANG = "en";
  31. function getItem(key: string) {
  32. try {
  33. return localStorage.getItem(key);
  34. } catch {
  35. return null;
  36. }
  37. }
  38. function setItem(key: string, value: string) {
  39. try {
  40. localStorage.setItem(key, value);
  41. } catch {}
  42. }
  43. function getLanguage() {
  44. try {
  45. return navigator.language.toLowerCase();
  46. } catch {
  47. console.log("[Lang] failed to detect user lang.");
  48. return DEFAULT_LANG;
  49. }
  50. }
  51. export function getLang(): Lang {
  52. const savedLang = getItem(LANG_KEY);
  53. if (AllLangs.includes((savedLang ?? "") as Lang)) {
  54. return savedLang as Lang;
  55. }
  56. const lang = getLanguage();
  57. for (const option of AllLangs) {
  58. if (lang.includes(option)) {
  59. return option;
  60. }
  61. }
  62. return DEFAULT_LANG;
  63. }
  64. export function changeLang(lang: Lang) {
  65. setItem(LANG_KEY, lang);
  66. location.reload();
  67. }
  68. export default {
  69. en: EN,
  70. cn: CN,
  71. tw: TW,
  72. fr: FR,
  73. es: ES,
  74. it: IT,
  75. tr: TR,
  76. jp: JP,
  77. de: DE,
  78. vi: VI,
  79. ru: RU,
  80. cs: CS,
  81. }[getLang()] as typeof CN;