All files / src/development SwitchLanguage.tsx

6.66% Statements 1/15
0% Branches 0/4
0% Functions 0/4
6.66% Lines 1/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50                  7x                                                                                
import React, { ReactElement } from 'react';
import i18next from 'i18next';
import dayjs from 'dayjs';
import { Space } from 'antd';
import { useTranslation } from 'react-i18next';
import { openInfoNotification } from '@utils/NotificationUtils';
import { stopPropagationAndPreventDefault } from "../utils/ObjectUtils";
import { LanguageLocalStorageKey } from '@config/i18n';
 
const SwitchLanguage = (): ReactElement => {
  const { t } = useTranslation();
  const initLang = localStorage.getItem(LanguageLocalStorageKey) || 'zh';
  const [lang, setLang] = React.useState<string>(initLang);
  const changeLanguage = (e: React.MouseEvent<unknown>, langCode: string, langName: string): void => {
    stopPropagationAndPreventDefault(e);
    dayjs.locale(langCode);
    i18next.changeLanguage(langCode);
    setLang(langCode);
    localStorage.setItem(LanguageLocalStorageKey, langCode);
    openInfoNotification(t("Language switch notification", { lang: langName }));
  };
  const supportLangs: Array<{
    code: string;
    name: string;
    flag: string;
  }> = [
      { code: 'zh', name: '简体中文', flag: '中' },
      { code: 'en', name: 'English', flag: 'EN' },
    ];
  return (
    <div style={{ cursor: "pointer" }}>
      <Space>
        {supportLangs.map((l) => {
          return (
            <span
              key={l.code}
              onClick={(e) => changeLanguage(e, l.code, l.name)}
              className={lang === l.code ? "language-selected" : "language-unselected"}
            >
              {l.flag}
            </span>
          );
        })}
      </Space>
    </div>
  );
};
 
export default SwitchLanguage;