summaryrefslogtreecommitdiff
path: root/src/build/i18n.ts
blob: b9b7403214ccc78644d27bf384765bc32aa6a3f7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/**
 * Replace i18n texts
 */

import locale from '../../locales';

export default class Replacer {
	private lang: string;

	public pattern = /"%i18n:(.+?)%"|'%i18n:(.+?)%'|%i18n:(.+?)%/g;

	constructor(lang: string) {
		this.lang = lang;

		this.get = this.get.bind(this);
		this.replacement = this.replacement.bind(this);
	}

	private get(key: string) {
		const texts = locale[this.lang];

		if (texts == null) {
			console.warn(`lang '${this.lang}' is not supported`);
			return key; // Fallback
		}

		let text = texts;

		// Check the key existance
		const error = key.split('.').some(k => {
			if (text.hasOwnProperty(k)) {
				text = text[k];
				return false;
			} else {
				return true;
			}
		});

		if (error) {
			console.warn(`key '${key}' not found in '${this.lang}'`);
			return key; // Fallback
		} else {
			return text;
		}
	}

	public replacement(match, a, b, c) {
		const key = a || b || c;
		if (match[0] == '"') {
			return '"' + this.get(key).replace(/"/g, '\\"') + '"';
		} else if (match[0] == "'") {
			return '\'' + this.get(key).replace(/'/g, '\\\'') + '\'';
		} else {
			return this.get(key);
		}
	}
}