* @param translations
*/
constructor(translations) {
- this.store = translations;
+ this.store = new Map();
+ this.parseTranslations();
+ }
+
+ /**
+ * Parse translations out of the page and place into the store.
+ */
+ parseTranslations() {
+ const translationMetaTags = document.querySelectorAll('meta[name="translation"]');
+ for (let tag of translationMetaTags) {
+ const key = tag.getAttribute('key');
+ const value = tag.getAttribute('value');
+ this.store.set(key, value);
+ }
}
/**
* @returns {*}
*/
get(key, replacements) {
- let text = this.getTransText(key);
+ const text = this.getTransText(key);
return this.performReplacements(text, replacements);
}
* @returns {*}
*/
getPlural(key, count, replacements) {
- let text = this.getTransText(key);
- let splitText = text.split('|');
+ const text = this.getTransText(key);
+ const splitText = text.split('|');
+ const exactCountRegex = /^{([0-9]+)}/;
+ const rangeRegex = /^\[([0-9]+),([0-9*]+)]/;
let result = null;
- let exactCountRegex = /^{([0-9]+)}/;
- let rangeRegex = /^\[([0-9]+),([0-9*]+)]/;
- for (let i = 0, len = splitText.length; i < len; i++) {
- let t = splitText[i];
+ for (const i = 0, len = splitText.length; i < len; i++) {
+ const t = splitText[i];
// Parse exact matches
- let exactMatches = t.match(exactCountRegex);
+ const exactMatches = t.match(exactCountRegex);
if (exactMatches !== null && Number(exactMatches[1]) === count) {
result = t.replace(exactCountRegex, '').trim();
break;
}
// Parse range matches
- let rangeMatches = t.match(rangeRegex);
+ const rangeMatches = t.match(rangeRegex);
if (rangeMatches !== null) {
- let rangeStart = Number(rangeMatches[1]);
+ const rangeStart = Number(rangeMatches[1]);
if (rangeStart <= count && (rangeMatches[2] === '*' || Number(rangeMatches[2]) >= count)) {
result = t.replace(rangeRegex, '').trim();
break;
* @returns {String|Object}
*/
getTransText(key) {
- let splitKey = key.split('.');
- let value = splitKey.reduce((a, b) => {
- return a !== undefined ? a[b] : a;
- }, this.store);
+ const value = this.store.get(key);
if (value === undefined) {
- console.log(`Translation with key "${key}" does not exist`);
- value = key;
+ console.warn(`Translation with key "${key}" does not exist`);
}
return value;
*/
performReplacements(string, replacements) {
if (!replacements) return string;
- let replaceMatches = string.match(/:([\S]+)/g);
+ const replaceMatches = string.match(/:([\S]+)/g);
if (replaceMatches === null) return string;
replaceMatches.forEach(match => {
- let key = match.substring(1);
+ const key = match.substring(1);
if (typeof replacements[key] === 'undefined') return;
string = string.replace(match, replacements[key]);
});