website-gemompel/app/loc.js

100 lines
2.2 KiB
JavaScript
Raw Normal View History

2020-04-04 12:10:53 +00:00
/**
* the default language to use
*
* @var {string}
2020-04-04 12:33:48 +00:00
* @author svartoyg
2020-04-04 12:10:53 +00:00
*/
var _languageDefault = null;
/**
* the fallback language to use
*
* @var {string}
2020-04-04 12:33:48 +00:00
* @author svartoyg
2020-04-04 12:10:53 +00:00
*/
var _languageFallback = null;
/**
* two level map with ISO-639-1 code as first key and translation id as second key
*
* @var {Map<string,Map<string,string>>}
2020-04-04 12:33:48 +00:00
* @author svartoyg
2020-04-04 12:10:53 +00:00
*/
var _data = {};
/**
* @param {string} language
* @return Promise<Map<string,string>>
2020-04-04 12:33:48 +00:00
* @author svartoyg
2020-04-04 12:10:53 +00:00
*/
async function retrieveData (language) {
let json
try {
json = (await import(`../loc/${language}.json`)).default
} catch (exception) {
json = (await import(`../loc/${language.substr(0, language.indexOf('-'))}.json`)).default
}
const map = {}
flatten(json, '', map)
return map
}
function flatten (tree, prefix, result) {
for (const [key, value] of Object.entries(tree)) {
if (typeof value === 'string') {
result[prefix + key] = value
} else {
flatten(value, prefix + key + '.', result)
}
}
2020-04-04 12:10:53 +00:00
}
/**
* @param {string} languageDefault
* @param {string} [languageFallback]
2020-04-04 12:33:48 +00:00
* @author svartoyg
2020-04-04 12:10:53 +00:00
*/
export async function initialize (languageDefault, languageFallback = 'en') {
_languageFallback = languageFallback;
_languageDefault = languageDefault;
for (const language of [_languageFallback, _languageDefault]) {
if (_data.hasOwnProperty(language)) continue;
console.log('--', 'loading localization data for language "' + language + '" ...');
let data;
try {
data = await retrieveData(language);
2020-04-04 12:10:53 +00:00
} catch (exception) {
console.warn(exception.toString());
}
_data[language] = data;
}
}
/**
* gets a translation by its key for a specific language
*
* @param {string} key
* @param {string} [languageChosen]
* @return {string}
2020-04-04 12:33:48 +00:00
* @author svartoyg
2020-04-04 12:10:53 +00:00
*/
export function translate (key, languageChosen = _languageDefault) {
let result = undefined;
for (const language of [languageChosen, _languageFallback]) {
if (_data.hasOwnProperty(language) && (_data[language] !== undefined) && _data[language].hasOwnProperty(key)) {
result = _data[language][key];
break;
}
}
if (result === undefined) {
result = ('{{' + key + '}}');
}
return result;
}