phanpy/src/components/lang-selector.jsx

65 lines
1.8 KiB
React
Raw Normal View History

2024-08-13 15:26:23 +08:00
import { useLingui } from '@lingui/react';
import { useMemo } from 'preact/hooks';
2024-08-13 15:26:23 +08:00
import { DEFAULT_LANG, LOCALES } from '../locales';
import { activateLang } from '../utils/lang';
2024-08-13 15:26:23 +08:00
import localeCode2Text from '../utils/localeCode2Text';
export default function LangSelector() {
const { i18n } = useLingui();
const populatedLocales = useMemo(() => {
return LOCALES.map((lang) => {
const native = localeCode2Text({ code: lang, locale: lang });
const common = localeCode2Text(lang);
const showCommon = !!common && common !== native;
return {
code: lang,
native,
common,
showCommon,
};
}).sort((a, b) => {
// If pseudo-LOCALE, always put it at the bottom
if (a.code === 'pseudo-LOCALE') return 1;
if (b.code === 'pseudo-LOCALE') return -1;
// Sort by code
if (a.code < b.code) return -1;
if (a.code > b.code) return 1;
return 0;
});
}, [i18n.locale]);
2024-08-13 15:26:23 +08:00
return (
<label class="lang-selector">
🌐{' '}
<select
2024-08-15 17:34:24 +08:00
class="small"
2024-08-13 15:26:23 +08:00
value={i18n.locale || DEFAULT_LANG}
onChange={(e) => {
localStorage.setItem('lang', e.target.value);
activateLang(e.target.value);
}}
>
{populatedLocales.map(({ code, native, common, showCommon }) => {
if (code === 'pseudo-LOCALE') {
2024-08-13 15:26:23 +08:00
return (
<>
<hr />
<option value={code} key={code}>
2024-08-13 15:26:23 +08:00
Pseudolocalization (test)
</option>
</>
);
}
return (
<option value={code} key={code}>
{showCommon ? `${native} - ${common}` : native}
2024-08-13 15:26:23 +08:00
</option>
);
})}
</select>
</label>
);
}