75 lines
2.4 KiB
TypeScript
75 lines
2.4 KiB
TypeScript
/**
|
|
* Compact language toggle for English / French.
|
|
*/
|
|
import LanguageRoundedIcon from '@mui/icons-material/LanguageRounded';
|
|
import { Button, Menu, MenuItem, Tooltip } from '@mui/material';
|
|
import { useState } from 'react';
|
|
import { useTranslation } from 'react-i18next';
|
|
import { LOCALE_STORAGE_KEY, normalizeLocale, type AppLocale } from './index';
|
|
|
|
const OPTIONS: { code: AppLocale; labelKey: 'common.english' | 'common.french' }[] = [
|
|
{ code: 'en', labelKey: 'common.english' },
|
|
{ code: 'fr', labelKey: 'common.french' },
|
|
];
|
|
|
|
const ABBREV: Record<AppLocale, string> = { en: 'EN', fr: 'FR' };
|
|
|
|
type LanguageSwitcherProps = {
|
|
/** Show "EN"/"FR" (default) or full language name. */
|
|
display?: 'abbrev' | 'full';
|
|
};
|
|
|
|
export function LanguageSwitcher({ display = 'abbrev' }: LanguageSwitcherProps) {
|
|
const { t, i18n } = useTranslation();
|
|
const [anchor, setAnchor] = useState<null | HTMLElement>(null);
|
|
const current = normalizeLocale(i18n.language);
|
|
const currentOption = OPTIONS.find((o) => o.code === current) ?? OPTIONS[0];
|
|
const currentLabel =
|
|
display === 'full' ? t(currentOption.labelKey) : ABBREV[current];
|
|
|
|
const select = async (code: AppLocale) => {
|
|
setAnchor(null);
|
|
if (code === current) return;
|
|
try {
|
|
localStorage.setItem(LOCALE_STORAGE_KEY, code);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
await i18n.changeLanguage(code);
|
|
};
|
|
|
|
return (
|
|
<>
|
|
<Tooltip title={t('common.language')}>
|
|
<Button
|
|
size="small"
|
|
color="inherit"
|
|
aria-label={`${t('common.language')}: ${t(currentOption.labelKey)}`}
|
|
onClick={(e) => setAnchor(e.currentTarget)}
|
|
startIcon={<LanguageRoundedIcon fontSize="small" />}
|
|
sx={{
|
|
minWidth: 0,
|
|
px: 1.25,
|
|
fontWeight: 800,
|
|
letterSpacing: display === 'abbrev' ? '0.04em' : undefined,
|
|
border: '1px solid rgba(255,255,255,0.15)',
|
|
}}
|
|
>
|
|
{currentLabel}
|
|
</Button>
|
|
</Tooltip>
|
|
<Menu anchorEl={anchor} open={!!anchor} onClose={() => setAnchor(null)}>
|
|
{OPTIONS.map((opt) => (
|
|
<MenuItem
|
|
key={opt.code}
|
|
selected={opt.code === current}
|
|
onClick={() => void select(opt.code)}
|
|
>
|
|
{display === 'abbrev' ? `${ABBREV[opt.code]} — ${t(opt.labelKey)}` : t(opt.labelKey)}
|
|
</MenuItem>
|
|
))}
|
|
</Menu>
|
|
</>
|
|
);
|
|
}
|