This repository was archived by the owner on Feb 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 543
Expand file tree
/
Copy pathi18n.js
More file actions
78 lines (70 loc) · 2.38 KB
/
i18n.js
File metadata and controls
78 lines (70 loc) · 2.38 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import sha1 from 'sha1';
import RenderHTML from 'react-render-html';
import zhTw from './translations/zh_TW/i10n.json';
import zhCn from './translations/zh_CN/i10n.json';
import it from './translations/it_IT/i10n.json';
import vi from './translations/vi_VN/i10n.json';
import pl from './translations/pl_PL/i10n.json';
import ru from './translations/ru_RU/i10n.json';
import pt from './translations/pt_PT/i10n.json';
import es from './translations/es_ES/i10n.json';
import fr from './translations/fr_FR/i10n.json';
import en from './translations/en/i10n.json';
import ach from './translations/ach_UG/i10n.json';
export const supportedLanguages = {
zh_tw: zhTw,
zh_cn: zhCn,
it,
vi,
pl,
ru,
pt,
es,
fr,
en,
ach,
};
const fallbackLang = en;
let translation = {};
const t = key => (key in translation ? translation[key] : fallbackLang[key]);
export const init = lang => {
translation = supportedLanguages[lang];
};
export const i18nTranslate = str => (str && t(sha1(str))) || str;
export const translate = (input, params = []) => {
if (params.length) {
const stringToBeTranslated = input.replace(/\{\$({0-9])\}/gi, '%$1');
let translatedString = i18nTranslate(stringToBeTranslated);
params.forEach((replacement, index) => {
if (translatedString && typeof translatedString === 'string') {
translatedString = translatedString.replaceAll(`\{\$${index}\}`, replacement);
}
});
return RenderHTML(translatedString);
}
return i18nTranslate(input);
};
export const translateLangToLang = (str, fromLang, toLang) => {
if (supportedLanguages[fromLang]) {
const hashIndex = Object.values(supportedLanguages[fromLang]).findIndex(translatedStr => str === translatedStr);
if (hashIndex !== -1) {
const hash = Object.keys(supportedLanguages[fromLang])[hashIndex];
const translatedStr = supportedLanguages[toLang][hash];
if (translatedStr) {
return translatedStr;
}
}
}
return str;
};
export const xml = dom => {
const categories = Array.from(dom.getElementsByTagName('category') || []);
categories.forEach(child => {
const text = child.getAttribute('i18n-text');
if (text) {
child.setAttribute('name', translate(text));
}
xml(child);
});
return dom;
};