Files
monkey-ai-web/src/components/layout/headerbar/LanguageSelector.jsx
T

82 lines
3.0 KiB
React

/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { Globe as ActionGlobe } from '@/components/common/icons/ActionIcons';
import React, { useEffect, useState } from 'react';
import { Button as AntButton, Dropdown } from 'antd';
import { CN, GB, JP, KR, TH, VN } from 'country-flag-icons/react/3x2';
import { normalizeLanguage } from '../../../i18n/language';
import { orderEnabledLanguages } from '../../../i18n/catalog';
import {
LANG_BOOT_UPDATED_EVENT,
getBootConfig,
} from '../../../i18n/bootstrap';
// 语言目录里的 flag 国家码 → 旗帜组件
const FLAGS = { CN, GB, JP, KR, TH, VN };
const LanguageSelector = ({ currentLang, onLanguageChange, t }) => {
// i18n.language 可能带地区码(如 zh-CN / en-US),高亮判断先归一化;
// 繁体靠地区码区分,不能简单取主语言
const lang = normalizeLanguage(currentLang);
// 首访时后台判定可能晚于顶栏首次渲染:结果写入缓存后重新读取启用语言,
// 避免列出后台已停用的语言
const [, setBootVersion] = useState(0);
useEffect(() => {
const handleBootUpdated = () => setBootVersion((version) => version + 1);
window.addEventListener(LANG_BOOT_UPDATED_EVENT, handleBootUpdated);
return () =>
window.removeEventListener(LANG_BOOT_UPDATED_EVENT, handleBootUpdated);
}, []);
// 展示哪些语言、按什么顺序由后台「语言与地区」配置决定(经 /api/i18n/locale 缓存下发)
const languages = orderEnabledLanguages(getBootConfig()?.enabled_languages);
return (
<Dropdown
trigger={['hover', 'click']}
placement='bottomRight'
menu={{
selectable: true,
selectedKeys: [lang],
onClick: ({ key }) => onLanguageChange(key),
items: languages.map(({ code, endonym, flag }) => {
const Flag = FLAGS[flag];
return {
key: code,
icon: Flag ? <Flag title={endonym} className='w-5 h-auto' /> : null,
label: endonym,
};
}),
}}
>
<AntButton
type='text'
icon={<ActionGlobe size={16} strokeWidth={1.5} aria-hidden />}
aria-label={t('common.changeLanguage')}
aria-haspopup='menu'
className='ui-header-icon-action'
/>
</Dropdown>
);
};
export default LanguageSelector;