feat:support partial fields to set i18n lang
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import { ILang } from '../../interface/i18n/I18n'
|
||||
import zhCN from './lang/zh-CN.json'
|
||||
import en from './lang/en.json'
|
||||
import { mergeObject } from '../../utils'
|
||||
import { DeepPartial } from '../../interface/Common'
|
||||
|
||||
export class I18n {
|
||||
|
||||
@@ -11,8 +13,12 @@ export class I18n {
|
||||
|
||||
private currentLocale = 'zhCN'
|
||||
|
||||
public registerLangMap(locale: string, lang: ILang) {
|
||||
this.langMap.set(locale, lang)
|
||||
public registerLangMap(locale: string, lang: DeepPartial<ILang>) {
|
||||
const sourceLang = this.langMap.get(locale)
|
||||
this.langMap.set(
|
||||
locale,
|
||||
<ILang>mergeObject(sourceLang || zhCN, lang)
|
||||
)
|
||||
}
|
||||
|
||||
public setLocale(locale: string) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ContextMenu } from '../contextmenu/ContextMenu'
|
||||
import { Shortcut } from '../shortcut/Shortcut'
|
||||
import { I18n } from '../i18n/I18n'
|
||||
import { ILang } from '../../interface/i18n/I18n'
|
||||
import { DeepPartial } from '../../interface/Common'
|
||||
|
||||
interface IRegisterPayload {
|
||||
contextMenu: ContextMenu;
|
||||
@@ -15,7 +16,7 @@ export class Register {
|
||||
|
||||
public contextMenuList: (payload: IRegisterContextMenu[]) => void
|
||||
public shortcutList: (payload: IRegisterShortcut[]) => void
|
||||
public langMap: (locale: string, lang: ILang) => void
|
||||
public langMap: (locale: string, lang: DeepPartial<ILang>) => void
|
||||
|
||||
constructor(payload: IRegisterPayload) {
|
||||
const { contextMenu, shortcut, i18n } = payload
|
||||
|
||||
@@ -23,3 +23,7 @@ export type DeepRequired<T> = T extends Error
|
||||
: T extends {}
|
||||
? { [K in keyof T]-?: DeepRequired<T[K]> }
|
||||
: Required<T>
|
||||
|
||||
export type DeepPartial<T> = {
|
||||
[P in keyof T]?: DeepPartial<T[P]>;
|
||||
}
|
||||
@@ -88,3 +88,27 @@ function nClickEvent(n: number, dom: HTMLElement, fn: (evt: MouseEvent) => any)
|
||||
|
||||
dom.addEventListener('click', handler)
|
||||
}
|
||||
|
||||
export function isObject(type: unknown): type is Record<string, unknown> {
|
||||
return Object.prototype.toString.call(type) === '[object Object]'
|
||||
}
|
||||
|
||||
export function isArray(type: unknown): type is Array<unknown> {
|
||||
return Array.isArray(type)
|
||||
}
|
||||
|
||||
export function mergeObject<T>(source: T, target: T): T {
|
||||
if (isObject(source) && isObject(target)) {
|
||||
const objectTarget = <Record<string, unknown>>target
|
||||
for (const [key, val] of Object.entries(source)) {
|
||||
if (!objectTarget[key]) {
|
||||
objectTarget[key] = val
|
||||
} else {
|
||||
objectTarget[key] = mergeObject(val, objectTarget[key])
|
||||
}
|
||||
}
|
||||
} else if (isArray(source) && isArray(target)) {
|
||||
target.push(...source)
|
||||
}
|
||||
return target
|
||||
}
|
||||
Reference in New Issue
Block a user