/** @format */ import { isArray, isString } from '@vue/shared'; import { I18N_JSON_DELIMITERS, QIN_STORAGE_LOCALE, getEnvLocale, } from '@fe6/qinjs-shared'; import { type BuiltInLocale, initVueI18n, isI18nStr } from '@fe6/qinjs-i18n'; import { isEnableLocale } from './utils'; let i18n: ReturnType; function getLocaleMessage() { const locale = qin.getLocale(); const locales = __qinConfig.locales; return ( locales[locale] || locales[__qinConfig.fallbackLocale] || locales['zh-hans'] || {} ); } export function formatI18n(message: string) { if (isI18nStr(message, I18N_JSON_DELIMITERS)) { return useI18n().f(message, getLocaleMessage(), I18N_JSON_DELIMITERS); } return message; } function resolveJsonObj( jsonObj: Record | undefined, names: string[], ): Record | Array> | undefined { if (names.length === 1) { if (jsonObj) { const _isI18nStr = (value: any) => isString(value) && isI18nStr(value, I18N_JSON_DELIMITERS); const _name = names[0]; let filterJsonObj: Array> = []; if ( isArray(jsonObj) && (filterJsonObj = jsonObj.filter((item) => _isI18nStr(item[_name]))) .length ) { return filterJsonObj; } const value = (jsonObj as Record)[names[0]]; if (_isI18nStr(value)) { return jsonObj; } } return; } const name = names.shift()!; return resolveJsonObj(jsonObj && jsonObj[name], names); } export function defineI18nProperties( obj: Record, names: string[][], ) { return names.map((name) => defineI18nProperty(obj, name)); } export function defineI18nProperty(obj: Record, names: string[]) { const jsonObj = resolveJsonObj(obj, names); if (!jsonObj) { return false; } const prop = names[names.length - 1]; if (isArray(jsonObj)) { jsonObj.forEach((item) => defineI18nProperty(item, [prop])); } else { let value = jsonObj[prop]; Object.defineProperty(jsonObj, prop, { get() { return formatI18n(value); }, set(v) { value = v; }, }); } return true; } export function useI18n() { if (!i18n) { let locale: BuiltInLocale; if (__PLATFORM__ === 'h5') { if (__NODE_JS__) { locale = getEnvLocale() as BuiltInLocale; } else { locale = ((navigator.cookieEnabled && window.localStorage && localStorage[QIN_STORAGE_LOCALE]) || __qinConfig.locale || navigator.language) as BuiltInLocale; } } else { locale = qin.getSystemInfoSync().language as BuiltInLocale; } i18n = initVueI18n(locale); // 自定义locales if (isEnableLocale()) { const localeKeys = Object.keys(__qinConfig.locales || {}); if (localeKeys.length) { localeKeys.forEach((locale) => i18n.add(locale as BuiltInLocale, __qinConfig.locales[locale]), ); } // initVueI18n 时 messages 还没有,导致用户自定义 locale 可能不生效,当设置完 messages 后,重新设置 locale i18n.setLocale(locale); } } return i18n; }