]> BookStack Code Mirror - bookstack/blob - resources/assets/js/translations.js
Fixes #354, Adds the spellchecker option
[bookstack] / resources / assets / js / translations.js
1 /**
2  *  Translation Manager
3  *  Handles the JavaScript side of translating strings
4  *  in a way which fits with Laravel.
5  */
6 class Translator {
7
8     /**
9      * Create an instance, Passing in the required translations
10      * @param translations
11      */
12     constructor(translations) {
13         this.store = translations;
14     }
15
16     /**
17      * Get a translation, Same format as laravel's 'trans' helper
18      * @param key
19      * @param replacements
20      * @returns {*}
21      */
22     get(key, replacements) {
23         let splitKey = key.split('.');
24         let value = splitKey.reduce((a, b) => {
25             return a != undefined ? a[b] : a;
26         }, this.store);
27
28         if (value === undefined) {
29             console.log(`Translation with key "${key}" does not exist`);
30             value = key;
31         }
32
33         if (replacements === undefined) return value;
34
35         let replaceMatches = value.match(/:([\S]+)/g);
36         if (replaceMatches === null) return value;
37         replaceMatches.forEach(match => {
38             let key = match.substring(1);
39             if (typeof replacements[key] === 'undefined') return;
40             value = value.replace(match, replacements[key]);
41         });
42         return value;
43     }
44
45 }
46
47 export default Translator