index.ts 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. export type { LocaleType } from "./cn";
  10. export const AllLangs = [
  11. "en",
  12. "cn",
  13. "tw",
  14. "es",
  15. "it",
  16. "tr",
  17. "jp",
  18. "de",
  19. ] as const;
  20. type Lang = (typeof AllLangs)[number];
  21. const LANG_KEY = "lang";
  22. function getItem(key: string) {
  23. try {
  24. return localStorage.getItem(key);
  25. } catch {
  26. return null;
  27. }
  28. }
  29. function setItem(key: string, value: string) {
  30. try {
  31. localStorage.setItem(key, value);
  32. } catch {}
  33. }
  34. function getLanguage() {
  35. try {
  36. return navigator.language.toLowerCase();
  37. } catch {
  38. return "cn";
  39. }
  40. }
  41. export function getLang(): Lang {
  42. const savedLang = getItem(LANG_KEY);
  43. if (AllLangs.includes((savedLang ?? "") as Lang)) {
  44. return savedLang as Lang;
  45. }
  46. const lang = getLanguage();
  47. for (const option of AllLangs) {
  48. if (lang.includes(option)) {
  49. return option;
  50. }
  51. }
  52. return "en";
  53. }
  54. export function changeLang(lang: Lang) {
  55. setItem(LANG_KEY, lang);
  56. location.reload();
  57. }
  58. export default {
  59. en: EN,
  60. cn: CN,
  61. tw: TW,
  62. es: ES,
  63. it: IT,
  64. tr: TR,
  65. jp: JP,
  66. de: DE,
  67. }[getLang()] as typeof CN;