import {isUndefined, merge, snakeCase} from 'lodash-es' import {codeWarningOnce} from '@befe/brick-utils'; import { DEFAULT_LOCALE, ComponentLocale, disposeLocaleText, StandardLocaleDict, normalizeKeyToSnakeCaseDeep, LocaleDict, } from './locale' export class I18n { // all keys should be snake_case, see ./locale for more detail private locale = DEFAULT_LOCALE readonly localeDict: StandardLocaleDict = {} constructor(locale = DEFAULT_LOCALE, localeDict?: LocaleDict) { this.setLocale(locale, localeDict) } setLocale(locale = DEFAULT_LOCALE, localeDict?: LocaleDict) { this.locale = snakeCase(locale) if (!isUndefined(localeDict)) { this.setLocaleDict(localeDict) } } setLocaleDict(localeDict: LocaleDict) { merge(this.localeDict, normalizeKeyToSnakeCaseDeep(localeDict)) } getLocaleText( componentLocale: ComponentLocale, key: string, ...args: any[] ) { const {defaultLocaleDict, componentName} = componentLocale // 从全局 localSet 中获取此组件在当前语言词库 const localePackMap = this.localeDict[this.locale] || {} const localePackFromConfig = localePackMap[componentName] || {} // 组件默认的当前语言词库 const localePackDefault = defaultLocaleDict[this.locale] const compLocale = merge(localePackDefault, localePackFromConfig) // console.log(localePackMap, defaultLocaleDict) const text = compLocale[key] if (typeof text === 'function') { return text(...args) } codeWarningOnce( typeof text !== 'undefined', 'i18n key {%s} 未能找到', key ) return disposeLocaleText(text, ...args) } }