press-plus
Version:
111 lines (88 loc) • 2.41 kB
text/typescript
import { deepAssign } from 'press-ui/common/utils/object-assign';
// #ifndef VUE3
import { Vue } from 'press-ui/common/vue3/vue';
// #endif
import template from './format';
import defaultLang from './lang/zh-CN';
let lang: Record<string, any> = defaultLang;
let merged = false;
let i18nHandler = function (this: Object, ...args: any[]) {
try {
// #ifdef H5
if (typeof (window as any).app?.$t === 'function') {
return (window as any).app?.$t.apply(this, args);
}
// #endif
} catch (err) {}
// #ifndef VUE3
const vuei18n = Object.getPrototypeOf(this || Vue)?.$t;
if (typeof vuei18n === 'function' && !!(Vue as any).locale) {
if (!merged) {
merged = true;
(Vue as any).locale(
(Vue.config as any).lang,
deepAssign((Vue as any)?.locale?.((Vue.config as any).lang) || {}, lang),
);
}
return vuei18n.apply(this, args);
}
// #endif
return;
};
export const t = function (this: any, path = '', ...options: Array<any>): any {
let value = i18nHandler.apply(this, [path, ...options]);
if (value !== null && value !== undefined) return value;
const array = path.split('.');
let current = lang;
for (let i = 0, j = array.length; i < j; i++) {
const property = array[i];
value = current[property];
if (i === j - 1) {
// 如果没有找到value,就从第一层找
if (!value) {
return lang[property] || '';
}
if (typeof value === 'function') {
return value(...options);
}
return value;
// return format(value, options);
}
if (!value) {
return lang[array[array.length - 1]] || '';
}
current = value;
}
return '';
};
export const use = function (l?: Record<string, any>) {
lang = l || lang;
};
export const i18n = function (fn?: any) {
i18nHandler = fn || i18nHandler;
};
export const add = function (messages = {}) {
deepAssign(lang, messages);
};
export const getLang = function () {
return lang;
};
export const tWithDefault = function (this: any, path = '', ...options: Array<any>) {
const result = t.call(this, path, ...options);
if (result) {
return result;
}
let value = path;
if (!options?.[1]?.ignoreDot) {
const list = path.split('.');
value = list[list.length - 1] || '';
}
return template(value, ...options);
};
export default {
use,
t,
i18n,
add,
getLang,
};