-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
114 lines (101 loc) · 2.26 KB
/
index.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
const gettextParser = require('gettext-parser')
const fs = require('fs')
const path = require('path')
let defaultLang, translations, prefix, suffix, regex
class Resources {
constructor (options) {
this.options = {
lang: 'en',
translations: {},
prefix: '${',
suffix: '}',
regex: /\${(\d*)}/g,
...options
}
defaultLang = this.options.lang
translations = this.options.translations
prefix = this.options.prefix
suffix = this.options.suffix
regex = this.options.regex
translations[defaultLang] = {
msgid: '',
comments: {},
msgstr: ['']
}
}
load (lang, resourceFile) {
const fileRaw = fs.readFileSync(path.resolve(resourceFile))
const po = gettextParser.po.parse(fileRaw)
translations[lang] = po.translations['']
translations[lang][''][''] = {
msgid: '',
comments: {},
msgstr: ['']
}
return translations[lang]
}
remove (lang) {
translations[lang] = {}
return true
}
}
class Translation {
constructor (lang) {
this.lang = lang || defaultLang
if (!translations[this.lang]) {
console.error('Without resources')
}
}
getTranslation (msgid) {
msgid = msgid.toString()
const translation = translations[this.lang][msgid] || {
msgid: msgid,
comments: {},
msgstr: [msgid]
}
if (translation.msgstr.toString() == '') {
translation.msgstr = [msgid]
}
return translation
}
getMsgid (str, exp) {
let n = 0
if (str.reduce && exp) {
return str.reduce((total, current, index) => {
let select = `${prefix}${n}${suffix}`
n++
if (exp[index] === undefined) {
select = ''
}
return `${total}${current}${select}`
}, '')
}
return str
}
_ (str, ...exp) {
const msgid = this.getMsgid(str, exp)
const msgstr = this.getTranslation(msgid).msgstr
if (str.reduce && exp) {
return msgstr.toString().replace(regex, (match, key) => {
return exp[Number(key)]
}, '')
}
return msgstr.toString()
}
msgid (str, ...exp) {
const msgid = this.getMsgid(str, exp)
return this.getTranslation(msgid)
}
msgstr (str, ...exp) {
const msgid = this.getMsgid(str, exp)
return this.getTranslation(msgid).msgstr
}
comments (str, ...exp) {
const msgid = this.getMsgid(str, exp)
return this.getTranslation(msgid).comments
}
}
module.exports = {
Resources,
Translation
}