index.ts 1.5 KB

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