-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathLanguageSelector.tsx
111 lines (102 loc) · 2.72 KB
/
LanguageSelector.tsx
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/*
* Copyright The OpenZipkin Authors
* SPDX-License-Identifier: Apache-2.0
*/
import { Button, Menu, MenuItem } from '@material-ui/core';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import TranslateIcon from '@material-ui/icons/Translate';
import React, { useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { FALLBACK_LOCALE } from '../../translations/i18n';
// We want to display all the languages in native language, not current locale, so hard-code the
// strings here instead of using internationalization.
//
// Exported for testing
export const LANGUAGES = [
{
locale: 'en',
name: 'English',
iso6391: 'EN',
},
{
locale: 'es',
name: 'Español',
iso6391: 'ES',
},
{
locale: 'fr',
name: 'Français',
iso6391: 'FR',
},
{
locale: 'zh_cn',
name: '中文 (简体)',
iso6391: 'ZH',
},
];
const LanguageSelector = () => {
const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);
const { i18n } = useTranslation();
const handleButtonClick = useCallback(
(event: React.MouseEvent<HTMLButtonElement>) => {
event.preventDefault();
setAnchorEl(event.currentTarget);
},
[],
);
const handleMenuClose = useCallback(() => {
setAnchorEl(null);
}, []);
const handleMenuItemClick = useCallback(
(event: React.MouseEvent<HTMLLIElement>) => {
setAnchorEl(null);
const { locale } = event.currentTarget.dataset;
if (!locale) {
return;
}
if (locale === i18n.language) {
return;
}
i18n.changeLanguage(locale);
},
[i18n],
);
useEffect(() => {
if (LANGUAGES.find((lang) => lang.locale === i18n.language)) {
i18n.changeLanguage(i18n.language);
} else {
i18n.changeLanguage(FALLBACK_LOCALE); // fallback to default language if the selected language is not supported
}
}, [i18n]);
return (
<>
<Button
onClick={handleButtonClick}
startIcon={<TranslateIcon />}
endIcon={<ExpandMoreIcon />}
data-testid="change-language-button"
>
{LANGUAGES.find((lang) => lang.locale === i18n.language)?.iso6391}
</Button>
<Menu
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleMenuClose}
>
{LANGUAGES.map((lang) => (
<MenuItem
key={lang.locale}
onClick={handleMenuItemClick}
selected={lang.locale === i18n.language}
data-locale={lang.locale}
data-testid={`language-list-item-${lang.locale}`}
>
{lang.name}
</MenuItem>
))}
</Menu>
</>
);
};
export default LanguageSelector;