All files / src/components/LanguageSelector LanguageSelector.tsx

100% Statements 16/16
100% Branches 4/4
100% Functions 5/5
100% Lines 15/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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 741x                   1x 9x 9x 9x 9x 9x   9x 2x   1x 1x 1x       9x                                                     27x                 2x                      
'use client';
 
import { ActionIcon, Menu, useMantineTheme } from '@mantine/core';
import { useRouter } from 'next/navigation';
import { useLocale, useTranslations } from 'next-intl';
import { type FC, useTransition } from 'react';
import { FiCheck, FiGlobe } from 'react-icons/fi';
import { LANGUAGES } from '@/i18n/languages';
import { setStoredLocale } from '@/lib/locale/locale.client';
 
const LanguageSelector: FC = () => {
  const translate = useTranslations('common');
  const locale = useLocale();
  const router = useRouter();
  const theme = useMantineTheme();
  const [isPending, startTransition] = useTransition();
 
  const handleLanguageChange = (newLocale: string) => {
    if (newLocale === locale) return;
 
    setStoredLocale(newLocale);
    startTransition(() => {
      router.refresh();
    });
  };
 
  return (
    <Menu
      shadow="md"
      width={200}
      position="bottom-end"
      withinPortal={false}
      offset={4}
      transitionProps={{ duration: 150 }}
      closeOnClickOutside
      middlewares={{ flip: true, shift: true, inline: false }}
    >
      <Menu.Target>
        <ActionIcon
          variant="subtle"
          color="gray"
          size="lg"
          loading={isPending}
          aria-label={translate('languageSelector')}
          data-testid="language-selector-button"
        >
          <FiGlobe size={20} />
        </ActionIcon>
      </Menu.Target>
 
      <Menu.Dropdown>
        <Menu.Label>{translate('language')}</Menu.Label>
        {LANGUAGES.map((lang) => (
          <Menu.Item
            key={lang.code}
            data-testid={`language-item-${lang.code}`}
            leftSection={<span style={{ fontSize: 18 }}>{lang.flag}</span>}
            rightSection={
              lang.code === locale ? (
                <FiCheck size={16} color={theme.colors.pink[7]} />
              ) : null
            }
            onClick={() => handleLanguageChange(lang.code)}
          >
            {lang.label}
          </Menu.Item>
        ))}
      </Menu.Dropdown>
    </Menu>
  );
};
 
export default LanguageSelector;