-
Notifications
You must be signed in to change notification settings - Fork 3.4k
Supports multiple languages in the web interface #4712
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Open
Changes from 1 commit
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
0e039e7
Supports multiple languages in the web interface. The interface will ...
QiMa ea081eb
supports multiple languages in the web interface
QiMa 155c754
Enhance i18n Translation Function,Fix i18n Initialization in Main App...
QiMa 03b0548
Fixed ESLint Errors in CI
QiMa File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
supports multiple languages in the web interface
- Loading branch information
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
219 changes: 182 additions & 37 deletions
frontend/js/app/i18n.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,65 +1,210 @@ | ||
| const Cache = require('./cache'); | ||
|
|
||
| // 使用分离的语言文件 | ||
| let messages = {}; | ||
| let isInitialized = false; | ||
| let currentLocale = null; | ||
|
|
||
| // 使用 webpack 的 require.context 显式包含可用语言资源,避免动态 require 被丢弃 | ||
| let localesContext = null; | ||
| try { | ||
| // 仅匹配现有语言文件;使用完整的locale格式 | ||
| localesContext = require.context('../i18n', false, /^\.\/(en-US|zh-CN|zh-TW|fr-FR|ja-JP|ko-KR|ru-RU|pt-PT)\.json$/); | ||
| } catch (e) { | ||
| // 非 webpack 环境下忽略 | ||
| localesContext = null; | ||
| } | ||
|
|
||
| // 预加载英文作为默认后备语言 | ||
| function preloadEnglish() { | ||
| if (!messages['en-US']) { | ||
| try { | ||
| let mod = localesContext ? localesContext('./en-US.json') : require('../i18n/en-US.json'); | ||
| // 规范化 ESModule default 导出 | ||
| messages['en-US'] = (mod && mod.default) ? mod.default : mod; | ||
| console.info('Pre-loaded English language file as fallback'); | ||
|
|
||
| // 验证基本结构 | ||
| if (messages['en-US'] && typeof messages['en-US'] === 'object') { | ||
| if (messages['en-US'].str && messages['en-US'].login) { | ||
| console.info('English language file structure validated'); | ||
| } else { | ||
| console.warn('English language file missing expected sections:', Object.keys(messages['en-US'])); | ||
| } | ||
| } else { | ||
| console.warn('English language file is not an object:', typeof messages['en-US']); | ||
| } | ||
| } catch (e) { | ||
| console.error('Critical: Failed to load English language file:', e); | ||
| messages['en-US'] = {}; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // 获取 Cache 的函数,避免循环依赖问题 | ||
| function getCache() { | ||
| try { | ||
| return require('./cache'); | ||
| } catch (e) { | ||
| console.warn('Cache module not available during initialization'); | ||
| return { locale: 'en' }; | ||
| } | ||
| } | ||
|
|
||
| // 清理缓存函数 | ||
| function clearCache() { | ||
| console.log('Clearing i18n cache...'); | ||
| messages = {}; | ||
| isInitialized = false; | ||
| currentLocale = null; | ||
| } | ||
|
|
||
| // 初始化函数 - 确保基础语言文件已加载 | ||
| function initialize(forceReload = false) { | ||
| let Cache = getCache(); | ||
| let newLocale = Cache.locale || 'en'; | ||
|
|
||
| // 如果语言发生变化,清理缓存 | ||
| if (currentLocale && currentLocale !== newLocale) { | ||
| console.log('Language changed from', currentLocale, 'to', newLocale, 'clearing cache'); | ||
| clearCache(); | ||
| } | ||
|
|
||
| if (isInitialized && !forceReload && currentLocale === newLocale) { | ||
| return; | ||
| } | ||
|
|
||
| console.log('Initializing i18n system with locale:', newLocale); | ||
| preloadEnglish(); | ||
|
|
||
| // 预加载当前设置的语言 | ||
| loadMessages(newLocale); | ||
|
|
||
| currentLocale = newLocale; | ||
| isInitialized = true; | ||
| console.log('i18n system initialized successfully'); | ||
| } | ||
|
|
||
| function loadMessages(locale) { | ||
| // 确保英文后备语言已加载 | ||
| preloadEnglish(); | ||
|
|
||
| if (!messages[locale]) { | ||
| try { | ||
| messages[locale] = require('../i18n/' + locale + '.json'); | ||
| console.log('Loading language file for locale:', locale); | ||
| let mod = localesContext ? localesContext('./' + locale + '.json') : require('../i18n/' + locale + '.json'); | ||
| // 规范化 ESModule default 导出 | ||
| messages[locale] = (mod && mod.default) ? mod.default : mod; | ||
| console.info('Successfully loaded language file:', locale); | ||
|
|
||
| // 验证基本结构 | ||
| if (messages[locale] && typeof messages[locale] === 'object') { | ||
| console.info('Language file structure for', locale, ':', Object.keys(messages[locale])); | ||
| } else { | ||
| console.warn('Language file is not an object for locale:', locale, typeof messages[locale]); | ||
| } | ||
| } catch (e) { | ||
| console.error('Language file not found for locale:', locale, e); | ||
| // 如果找不到语言文件,尝试加载英文作为后备 | ||
| if (locale !== 'en') { | ||
| try { | ||
| messages[locale] = require('../i18n/en.json'); | ||
| console.warn('Using English fallback for locale:', locale); | ||
| } catch (fallbackError) { | ||
| console.error('Failed to load fallback language file (en.json):', fallbackError); | ||
| messages[locale] = {}; | ||
| } | ||
| // 如果找不到语言文件,使用英文作为后备 | ||
| if (locale !== 'en-US') { | ||
| console.warn('Using English fallback for locale:', locale); | ||
| messages[locale] = messages['en-US'] || {}; | ||
| } else { | ||
| console.error('Failed to load English language file'); | ||
| messages[locale] = {}; | ||
| } | ||
| } | ||
| } else { | ||
| console.debug('Language file already loaded for locale:', locale); | ||
| } | ||
| return messages[locale]; | ||
| } | ||
|
|
||
| /** | ||
| * 主翻译函数 | ||
| * @param {String} namespace | ||
| * @param {String} key | ||
| * @param {Object} [data] | ||
| */ | ||
| module.exports = function (namespace, key, data) { | ||
| let locale = Cache.locale; | ||
| let currentMessages = loadMessages(locale); | ||
|
|
||
| // 检查当前语言是否有对应的翻译 | ||
| if (currentMessages && currentMessages[namespace] && typeof currentMessages[namespace][key] !== 'undefined') { | ||
| try { | ||
| return currentMessages[namespace][key](data); | ||
| } catch (formatError) { | ||
| console.error('Error formatting message:', namespace, key, formatError); | ||
| return currentMessages[namespace][key].toString(); | ||
| function translate(namespace, key, data) { | ||
| try { | ||
| let Cache = getCache(); | ||
| let locale = Cache.locale || 'en'; // 确保总是有一个有效的locale | ||
|
|
||
| // 检查语言是否发生变化,如果变化则重新初始化 | ||
| if (currentLocale !== locale) { | ||
| console.log('Detected locale change in translate function:', currentLocale, '->', locale); | ||
| initialize(true); // 强制重新初始化 | ||
| } | ||
| } | ||
|
|
||
| // 如果当前语言没有翻译,尝试使用英文作为后备 | ||
| if (locale !== 'en') { | ||
| let enMessages = loadMessages('en'); | ||
| if (enMessages && enMessages[namespace] && typeof enMessages[namespace][key] !== 'undefined') { | ||
| try { | ||
| return enMessages[namespace][key](data); | ||
| } catch (formatError) { | ||
| console.error('Error formatting English fallback message:', namespace, key, formatError); | ||
| return enMessages[namespace][key].toString(); | ||
|
|
||
| // 确保系统已初始化 | ||
| if (!isInitialized) { | ||
| initialize(); | ||
| } | ||
|
|
||
| let currentMessages = loadMessages(locale); | ||
|
|
||
| // 如果没有加载到任何消息,强制使用英文 | ||
| if (!currentMessages) { | ||
| console.warn('No messages loaded for locale:', locale, 'forcing English'); | ||
| currentMessages = loadMessages('en'); | ||
| locale = 'en'; | ||
| } | ||
|
|
||
| // MessageFormat loader保持JSON结构,只是将字符串转换为函数 | ||
| // 尝试获取翻译 | ||
| function getTranslation(messages, namespace, key, data) { | ||
| if (!messages || typeof messages !== 'object') { | ||
| return null; | ||
| } | ||
|
|
||
| if (messages[namespace] && typeof messages[namespace][key] !== 'undefined') { | ||
| try { | ||
| let value = messages[namespace][key]; | ||
| // MessageFormat loader将字符串转换为函数 | ||
| if (typeof value === 'function') { | ||
| return value(data || {}); | ||
| } else { | ||
| // 如果还是字符串,直接返回 | ||
| return value; | ||
| } | ||
| } catch (formatError) { | ||
| console.error('Error formatting message:', namespace, key, formatError); | ||
| // 尝试返回原始值 | ||
| try { | ||
| return messages[namespace][key].toString(); | ||
| } catch (e) { | ||
| return null; | ||
| } | ||
| } | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| // 尝试从当前语言获取翻译 | ||
| let result = getTranslation(currentMessages, namespace, key, data); | ||
| if (result !== null) { | ||
| return result; | ||
| } | ||
|
|
||
| // 如果当前语言没有翻译,尝试使用英文作为后备 | ||
| if (locale !== 'en') { | ||
| let enMessages = loadMessages('en'); | ||
| result = getTranslation(enMessages, namespace, key, data); | ||
| if (result !== null) { | ||
| return result; | ||
| } | ||
| } | ||
|
|
||
| console.warn('Missing translation:', namespace + '/' + key, 'for locale:', locale); | ||
| return '(MISSING: ' + namespace + '/' + key + ')'; | ||
|
|
||
| } catch (criticalError) { | ||
| console.error('Critical error in i18n translate function:', criticalError); | ||
| // 返回一个安全的fallback | ||
| return key || '(ERROR)'; | ||
| } | ||
| } | ||
|
|
||
| console.warn('Missing translation:', namespace + '/' + key, 'for locale:', locale); | ||
| return '(MISSING: ' + namespace + '/' + key + ')'; | ||
| }; | ||
| // 导出主翻译函数和相关函数 | ||
| module.exports = translate; | ||
| module.exports.initialize = initialize; | ||
| module.exports.clearCache = clearCache; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.