- 移除 useGameBoardVm 数据层实施说明文档 - 移除核心玩法与前端规则摘要文档 - 移除游戏模块数据与界面分层第一阶段实施稿文档 - 清理与数据层重构相关的技术方案说明 - 删除关于 PC 和 Mobile 界面分离的设计规划 - 移除 view-model hooks 架构设计相关内容
86 lines
2.1 KiB
TypeScript
86 lines
2.1 KiB
TypeScript
import i18n from 'i18next'
|
|
import { initReactI18next } from 'react-i18next'
|
|
|
|
import { DEFAULT_APP_LANGUAGE, SUPPORTED_LANGUAGES } from '@/constants/system'
|
|
import enUS from '@/locales/en-US'
|
|
import idID from '@/locales/id-ID'
|
|
import msMY from '@/locales/ms-MY'
|
|
import zhCN from '@/locales/zh-CN'
|
|
import { getStoredAppLanguage, setStoredAppLanguage } from '@/store/auth'
|
|
|
|
export type { AppLanguage } from '@/type'
|
|
|
|
/** @description 判断给定语言是否在当前应用支持列表中。 */
|
|
export function isSupportedLanguage(
|
|
value: string | null | undefined,
|
|
): value is AppLanguage {
|
|
return SUPPORTED_LANGUAGES.includes(value as AppLanguage)
|
|
}
|
|
|
|
/** @description 获取应用启动时应使用的初始语言。 */
|
|
function getInitialLanguage() {
|
|
const persistedLanguage = getStoredAppLanguage()
|
|
|
|
if (isSupportedLanguage(persistedLanguage)) {
|
|
return persistedLanguage
|
|
}
|
|
|
|
return DEFAULT_APP_LANGUAGE
|
|
}
|
|
|
|
/** @description 暴露当前应用应优先使用的语言。 */
|
|
export function getPreferredLanguage() {
|
|
return getInitialLanguage()
|
|
}
|
|
|
|
/** @description 从路由路径中解析语言前缀。 */
|
|
export function getLanguageFromPathname(pathname: string) {
|
|
const [, firstSegment] = pathname.split('/')
|
|
|
|
if (isSupportedLanguage(firstSegment)) {
|
|
return firstSegment
|
|
}
|
|
|
|
return null
|
|
}
|
|
|
|
void i18n.use(initReactI18next).init({
|
|
lng: getInitialLanguage(),
|
|
fallbackLng: DEFAULT_APP_LANGUAGE,
|
|
debug: false,
|
|
interpolation: {
|
|
escapeValue: false,
|
|
},
|
|
resources: {
|
|
'zh-CN': {
|
|
common: zhCN,
|
|
},
|
|
'en-US': {
|
|
common: enUS,
|
|
},
|
|
'ms-MY': {
|
|
common: msMY,
|
|
},
|
|
'id-ID': {
|
|
common: idID,
|
|
},
|
|
},
|
|
defaultNS: 'common',
|
|
})
|
|
|
|
/** @description 同步当前语言到 html 标签并持久化到浏览器。 */
|
|
function syncLanguageState(language: string) {
|
|
if (typeof document !== 'undefined') {
|
|
document.documentElement.lang = language
|
|
}
|
|
|
|
if (isSupportedLanguage(language)) {
|
|
setStoredAppLanguage(language)
|
|
}
|
|
}
|
|
|
|
syncLanguageState(i18n.resolvedLanguage ?? DEFAULT_APP_LANGUAGE)
|
|
i18n.on('languageChanged', syncLanguageState)
|
|
|
|
export default i18n
|