@darwino/darwino
Version:
A set of Javascript classes and utilities
82 lines (77 loc) • 2.26 kB
JavaScript
/*!COPYRIGHT HEADER! - CONFIDENTIAL
*
* Darwino Inc Confidential.
*
* (c) Copyright Darwino Inc. 2014-2016.
*
* Notice: The information contained in the source code for these files is the property
* of Darwino Inc. which, with its licensors, if any, owns all the intellectual property
* rights, including all copyright rights thereto. Such information may only be used
* for debugging, troubleshooting and informational purposes. All other uses of this information,
* including any production or commercial uses, are prohibited.
*/
import {fetchJson} from './Fetch';
//
// I18N Utilities for Darwino
//
class I18NContext {
_listeners = []
_locale = "en"
_messages = {}
_context = {
"globalLocale": "en",
"userLocale": "en",
"supportedLocales": []
}
_debug = false
getContext() {
return this._context
}
getLocale() {
return this._locale
}
getMessages(locale) {
return this._messages[locale||this._locale];
}
setMessages(locale,messages) {
this._messages[locale] = messages;
}
addMessages(locale,messages) {
this._messages[locale] = Object.assign(this._messages[locale]||{},messages);
}
setLocale(locale) {
if(this._locale!=locale) {
this._locale = locale
this._notifyListeners()
}
}
setDebug(debug) {
this._debug = debug
}
addListener(l) {
this._listeners.push(l)
}
removeListener(l) {
const index = this._listeners.indexOf(l)
if(index>=0) this._listeners.splice(index, 1)
}
loadServerContext() {
return fetchJson("$darwino-i18n").then(json => {
this._context = json
this._locale = json.userLocale
this._notifyListeners()
}).catch((e) => {
// Ok, we just ignore and assume the default
this._notifyListeners()
})
}
_notifyListeners() {
this._listeners.forEach( (l) => {l()})
}
}
export const I18N = new I18NContext();
export function _t(key,text) {
const msgs = I18N.getMessages();
return (msgs && msgs[key])
|| (text && (I18N._debug ? "<<"+text+">>" : text) || "!!"+key+"!!");
}