All files / src/components/LocaleSelector index.tsx

0% Statements 0/64
0% Branches 0/1
0% Functions 0/1
0% Lines 0/64

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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                                                                                                                 
import { useState, useContext, MouseEvent, useEffect, useMemo } from 'react';
import Button from '@mui/material/Button';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import { localeTextMap, defaultLang, LocaleType, LocaleContext } from '@/locales';

function getNewLocales(curLang: string, localeTextMapSource: { [lang in LocaleType]: string }) {
  let newLocalMap: any = { ...localeTextMapSource };
  delete newLocalMap[curLang];
  newLocalMap = { [curLang]: (localeTextMapSource as any)[curLang], ...newLocalMap };
  return newLocalMap;
}

export default function LocaleSelector() {
  const { lang, setLang } = useContext(LocaleContext);
  const [langText, setLangText] = useState<string>(getNewLocales(defaultLang, localeTextMap)[defaultLang]);
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const open = Boolean(anchorEl);

  const localeTexts = useMemo(() => getNewLocales(lang, localeTextMap), [lang]);

  const handleClick = (event: MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };
  const handleClose = () => {
    setAnchorEl(null);
  };
  const handleItemClick = ({ lang, langText }: { lang: LocaleType | string, langText: string }) => {
    setLang(lang as LocaleType);
    setLangText(langText);
    handleClose();
  };

  return (
    <div>
      <Button
        variant="contained"
        onClick={handleClick}
      >
        {langText}
      </Button>
      <Menu
        id="demo-positioned-menu"
        aria-labelledby="demo-positioned-button"
        anchorEl={anchorEl}
        open={open}
        onClose={handleClose}
        anchorOrigin={{
          vertical: 'top',
          horizontal: 'left'
        }}
        transformOrigin={{
          vertical: 'top',
          horizontal: 'left'
        }}
      >
        {Object.keys(localeTexts).map((lang: string) => (
          <MenuItem key={lang} onClick={() => handleItemClick({ lang, langText: localeTexts[lang as LocaleType] })}>
            {localeTexts[lang as LocaleType]}
          </MenuItem>))}
      </Menu>
    </div>
  );
}