jellyfish-web/src/scripts/globalize.js

277 lines
7.3 KiB
JavaScript
Raw Normal View History

2020-07-18 09:21:15 +01:00
import * as userSettings from 'userSettings';
import events from 'events';
2020-07-18 09:21:15 +01:00
/* eslint-disable indent */
2018-10-23 01:05:09 +03:00
2020-07-18 09:21:15 +01:00
const fallbackCulture = 'en-us';
const allTranslations = {};
let currentCulture;
let currentDateTimeCulture;
export function getCurrentLocale() {
return currentCulture;
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
export function getCurrentDateTimeLocale() {
return currentDateTimeCulture;
2018-10-23 01:05:09 +03:00
}
function getDefaultLanguage() {
2020-07-18 09:21:15 +01:00
const culture = document.documentElement.getAttribute('data-culture');
if (culture) {
return culture;
}
if (navigator.language) {
return navigator.language;
}
if (navigator.userLanguage) {
return navigator.userLanguage;
}
if (navigator.languages && navigator.languages.length) {
return navigator.languages[0];
}
return fallbackCulture;
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
export function updateCurrentCulture() {
let culture;
2018-10-23 01:05:09 +03:00
try {
culture = userSettings.language();
} catch (err) {
2020-02-16 03:44:43 +01:00
console.error('no language set in user settings');
}
culture = culture || getDefaultLanguage();
currentCulture = normalizeLocaleName(culture);
2020-07-18 09:21:15 +01:00
let dateTimeCulture;
2018-10-23 01:05:09 +03:00
try {
dateTimeCulture = userSettings.dateTimeLocale();
} catch (err) {
2020-02-16 03:44:43 +01:00
console.error('no date format set in user settings');
}
if (dateTimeCulture) {
currentDateTimeCulture = normalizeLocaleName(dateTimeCulture);
} else {
currentDateTimeCulture = currentCulture;
}
ensureTranslations(currentCulture);
2018-10-23 01:05:09 +03:00
}
function ensureTranslations(culture) {
2020-07-19 17:38:42 +02:00
for (const i in allTranslations) {
ensureTranslation(allTranslations[i], culture);
}
if (culture !== fallbackCulture) {
2020-07-19 17:38:42 +02:00
for (const i in allTranslations) {
ensureTranslation(allTranslations[i], fallbackCulture);
}
}
2018-10-23 01:05:09 +03:00
}
function ensureTranslation(translationInfo, culture) {
if (translationInfo.dictionaries[culture]) {
return Promise.resolve();
}
return loadTranslation(translationInfo.translations, culture).then(function (dictionary) {
translationInfo.dictionaries[culture] = dictionary;
});
2018-10-23 01:05:09 +03:00
}
function normalizeLocaleName(culture) {
// TODO remove normalizations
culture = culture.replace('_', '-');
// convert de-DE to de
2020-07-18 09:21:15 +01:00
const parts = culture.split('-');
if (parts.length === 2) {
if (parts[0].toLowerCase() === parts[1].toLowerCase()) {
culture = parts[0].toLowerCase();
}
}
2020-07-18 09:21:15 +01:00
const lower = culture.toLowerCase();
if (lower === 'ca-es') {
return 'ca';
}
// normalize Swedish
if (lower === 'sv-se') {
return 'sv';
}
return lower;
2018-10-23 01:05:09 +03:00
}
function getDictionary(module, locale) {
if (!module) {
module = defaultModule();
}
2020-07-18 09:21:15 +01:00
const translations = allTranslations[module];
if (!translations) {
return {};
}
return translations.dictionaries[locale];
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
export function register(options) {
2018-10-23 01:05:09 +03:00
allTranslations[options.name] = {
translations: options.strings || options.translations,
dictionaries: {}
};
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
export function loadStrings(options) {
const locale = getCurrentLocale();
const promises = [];
let optionsName;
if (typeof options === 'string') {
2019-04-20 20:44:42 +02:00
optionsName = options;
} else {
2019-04-20 20:44:42 +02:00
optionsName = options.name;
register(options);
}
2019-04-20 20:44:42 +02:00
promises.push(ensureTranslation(allTranslations[optionsName], locale));
promises.push(ensureTranslation(allTranslations[optionsName], fallbackCulture));
return Promise.all(promises);
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
const cacheParam = new Date().getTime();
2018-10-23 01:05:09 +03:00
function loadTranslation(translations, lang) {
lang = normalizeLocaleName(lang);
2020-07-18 09:21:15 +01:00
let filtered = translations.filter(function (t) {
return normalizeLocaleName(t.lang) === lang;
2018-10-23 01:05:09 +03:00
});
if (!filtered.length) {
filtered = translations.filter(function (t) {
return normalizeLocaleName(t.lang) === fallbackCulture;
});
}
return new Promise(function (resolve, reject) {
if (!filtered.length) {
resolve();
return;
}
2020-07-18 09:21:15 +01:00
let url = filtered[0].path;
url += url.indexOf('?') === -1 ? '?' : '&';
url += 'v=' + cacheParam;
2020-07-18 09:21:15 +01:00
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (this.status < 400) {
resolve(JSON.parse(this.response));
} else {
resolve({});
}
};
xhr.onerror = function () {
resolve({});
};
xhr.send();
});
2018-10-23 01:05:09 +03:00
}
function translateKey(key) {
2020-07-18 09:21:15 +01:00
const parts = key.split('#');
let module;
if (parts.length > 1) {
module = parts[0];
key = parts[1];
}
return translateKeyFromModule(key, module);
2018-10-23 01:05:09 +03:00
}
function translateKeyFromModule(key, module) {
2020-07-18 09:21:15 +01:00
let dictionary = getDictionary(module, getCurrentLocale());
if (!dictionary || !dictionary[key]) {
dictionary = getDictionary(module, fallbackCulture);
}
if (!dictionary) {
return key;
}
return dictionary[key] || key;
2018-10-23 01:05:09 +03:00
}
function replaceAll(str, find, replace) {
return str.split(find).join(replace);
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
export function translate(key) {
let val = translateKey(key);
for (let i = 1; i < arguments.length; i++) {
val = replaceAll(val, '{' + (i - 1) + '}', arguments[i]);
}
return val;
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
export function translateHtml(html, module) {
if (!module) {
module = defaultModule();
}
if (!module) {
throw new Error('module cannot be null or empty');
}
2020-07-18 09:21:15 +01:00
let startIndex = html.indexOf('${');
if (startIndex === -1) {
return html;
}
2018-10-23 01:05:09 +03:00
startIndex += 2;
2020-07-18 09:21:15 +01:00
const endIndex = html.indexOf('}', startIndex);
if (endIndex === -1) {
return html;
}
2020-07-18 09:21:15 +01:00
const key = html.substring(startIndex, endIndex);
const val = translateKeyFromModule(key, module);
html = html.replace('${' + key + '}', val);
return translateHtml(html, module);
2018-10-23 01:05:09 +03:00
}
2020-07-18 09:21:15 +01:00
let _defaultModule;
export function defaultModule(val) {
if (val) {
_defaultModule = val;
}
return _defaultModule;
2018-10-23 01:05:09 +03:00
}
updateCurrentCulture();
events.on(userSettings, 'change', function (e, name) {
if (name === 'language' || name === 'datetimelocale') {
updateCurrentCulture();
}
});
2020-07-18 09:21:15 +01:00
export default {
translate,
translateHtml,
loadStrings,
defaultModule,
getCurrentLocale,
getCurrentDateTimeLocale,
register,
updateCurrentCulture
};
/* eslint-enable indent */