3 * Handles the JavaScript side of translating strings
4 * in a way which fits with Laravel.
9 * Create an instance, Passing in the required translations
12 constructor(translations) {
13 this.store = new Map();
14 this.parseTranslations();
18 * Parse translations out of the page and place into the store.
21 const translationMetaTags = document.querySelectorAll('meta[name="translation"]');
22 for (let tag of translationMetaTags) {
23 const key = tag.getAttribute('key');
24 const value = tag.getAttribute('value');
25 this.store.set(key, value);
30 * Get a translation, Same format as laravel's 'trans' helper
35 get(key, replacements) {
36 const text = this.getTransText(key);
37 return this.performReplacements(text, replacements);
41 * Get pluralised text, Dependant on the given count.
42 * Same format at laravel's 'trans_choice' helper.
48 getPlural(key, count, replacements) {
49 const text = this.getTransText(key);
50 const splitText = text.split('|');
51 const exactCountRegex = /^{([0-9]+)}/;
52 const rangeRegex = /^\[([0-9]+),([0-9*]+)]/;
55 for (let t of splitText) {
56 // Parse exact matches
57 const exactMatches = t.match(exactCountRegex);
58 if (exactMatches !== null && Number(exactMatches[1]) === count) {
59 result = t.replace(exactCountRegex, '').trim();
63 // Parse range matches
64 const rangeMatches = t.match(rangeRegex);
65 if (rangeMatches !== null) {
66 const rangeStart = Number(rangeMatches[1]);
67 if (rangeStart <= count && (rangeMatches[2] === '*' || Number(rangeMatches[2]) >= count)) {
68 result = t.replace(rangeRegex, '').trim();
74 if (result === null && splitText.length > 1) {
75 result = (count === 1) ? splitText[0] : splitText[1];
78 if (result === null) {
79 result = splitText[0];
82 return this.performReplacements(result, replacements);
86 * Fetched translation text from the store for the given key.
88 * @returns {String|Object}
91 const value = this.store.get(key);
93 if (value === undefined) {
94 console.warn(`Translation with key "${key}" does not exist`);
101 * Perform replacements on a string.
102 * @param {String} string
103 * @param {Object} replacements
106 performReplacements(string, replacements) {
107 if (!replacements) return string;
108 const replaceMatches = string.match(/:([\S]+)/g);
109 if (replaceMatches === null) return string;
110 replaceMatches.forEach(match => {
111 const key = match.substring(1);
112 if (typeof replacements[key] === 'undefined') return;
113 string = string.replace(match, replacements[key]);
120 export default Translator;