habitica/website/common/script/i18n.js

67 lines
1.6 KiB
JavaScript
Raw Permalink Normal View History

import isString from 'lodash/isString';
import clone from 'lodash/clone';
import template from 'lodash/template';
2015-11-12 02:32:00 +00:00
2019-10-01 15:53:48 +00:00
const i18n = {
2015-11-12 02:32:00 +00:00
strings: null,
translations: {},
2015-11-15 14:16:55 +00:00
t, // eslint-disable-line no-use-before-define
};
function t (stringName) {
2019-10-09 14:51:17 +00:00
const args = Array.from(arguments); // eslint-disable-line prefer-rest-params
let vars = args[1];
2015-11-15 14:16:55 +00:00
let locale;
2019-10-09 14:51:17 +00:00
if (isString(args[1])) {
2015-11-15 14:16:55 +00:00
vars = null;
2019-10-09 14:51:17 +00:00
locale = args[1]; // eslint-disable-line prefer-destructuring
} else if (args[2]) {
locale = args[2]; // eslint-disable-line prefer-destructuring
2015-11-15 14:16:55 +00:00
}
2019-10-08 14:57:10 +00:00
const i18nNotSetup = !i18n.strings && !i18n.translations[locale];
2015-11-15 14:16:55 +00:00
if (!locale || i18nNotSetup) {
locale = 'en';
}
let string;
if (i18n.strings) {
string = i18n.strings[stringName];
} else {
string = i18n.translations[locale] && i18n.translations[locale][stringName];
}
2019-10-08 14:57:10 +00:00
const clonedVars = clone(vars) || {};
2015-11-15 14:16:55 +00:00
clonedVars.locale = locale;
if (string) {
try {
return template(string)(clonedVars);
2015-11-15 14:16:55 +00:00
} catch (_error) {
return `Error processing the string "${stringName}". Please see Help > Report a Bug.`;
2015-11-12 02:32:00 +00:00
}
2015-11-15 14:16:55 +00:00
} else {
let stringNotFound;
if (i18n.strings) {
stringNotFound = i18n.strings.stringNotFound;
} else if (i18n.translations[locale]) {
stringNotFound = i18n.translations[locale] && i18n.translations[locale].stringNotFound;
2015-11-12 02:32:00 +00:00
}
2015-11-15 14:16:55 +00:00
try {
return template(stringNotFound)({
2015-11-15 14:16:55 +00:00
string: stringName,
});
} catch (_error) {
return 'Error processing the string "stringNotFound". Please see Help > Report a Bug.';
2015-11-12 02:32:00 +00:00
}
}
2015-11-15 14:16:55 +00:00
}
2019-10-01 15:53:48 +00:00
export default i18n;