@winged/core
Version:
Morden webapp framekwork made only for ts developers. (UNDER DEVELOPMENT, PLEASE DO NOT USE)
73 lines (63 loc) • 2.08 kB
text/typescript
import { utils } from '../../utils'
import { DataPointExtension } from './DataPointExtension'
/**
* format :
* {{"@some.key.name:[default text]"}}
*/
export class I18nExtension extends DataPointExtension {
public static setMessages(messages: { [key: string]: string }) {
this.i18nMessages = messages
for (const id in this.translatableInstances) {
this.translatableInstances[id].requireUpdate()
}
}
public static getMessage(key: string) {
return this.i18nMessages[key]
}
public static registerInstance(instance: I18nExtension) {
const id = utils.generateId()
this.translatableInstances[id] = instance
return id
}
public static unregisterInstance(id: string) {
delete this.translatableInstances[id]
}
private static translatableInstances: { [id: string]: I18nExtension } = {}
private static i18nMessages: { [key: string]: string } = {}
private static valueMatcher = /^@([\w.]+)(?::(.+))?$/
private static messageTester = /@[\w.]+(?::.+)?/
private hasI18nMsg: boolean
private id: string
public init(expression: string): string {
if (I18nExtension.messageTester.test(expression)) {
this.hasI18nMsg = true
this.id = I18nExtension.registerInstance(this)
}
return expression
}
public onValueChange(value: string): string {
if (this.hasI18nMsg && value[0] === '@') {
const match = value.match(I18nExtension.valueMatcher)
if (!match) {
return value
} else {
const [key, defaultMsg] = match
if (I18nExtension.i18nMessages[key]) {
return I18nExtension.i18nMessages[key]
} else if (defaultMsg) {
console.warn(`[i18n] Can't find message for key:"${key}" using default value`)
return defaultMsg
} else {
console.error(
`[i18n] Can't find message for key:"${key}" and no default value provided, please set a default value`
)
return ''
}
}
}
return value
}
public onDestroy() {
I18nExtension.unregisterInstance(this.id)
}
}