forked from OIRNOIR/WackyWebM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
localization.js
53 lines (45 loc) · 1.47 KB
/
localization.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
const path = require('path')
const fs = require('fs')
const aliases = {
en_us: [/en([-_](au|bz|ca|cb|gb|in|ie|jm|nz|ph|za|tt|us))?/, /english/],
}
const translations = {}
const localesDir = path.join(__dirname, 'localizations')
for (const locale of fs.readdirSync(localesDir).filter((file) => file.endsWith('.json'))) {
try {
translations[locale.replace('.json', '')] = require(path.join(localesDir, locale))
} catch (e) {
console.warn(`loading translation file ${locale} failed`)
}
}
function findLocaleInAliases(l) {
for (const locale in aliases) {
for (const alias of aliases[locale]) {
if (alias.test(l)) {
return locale
}
}
}
return ''
}
let fallBackLocale = translations['en_us']
let currentLocale = fallBackLocale
function setLocale(l) {
l = l.toString().toLowerCase()
let localeName = findLocaleInAliases(l)
if (localeName === '')
localeName = l
console.log(localeName)
if (!translations[localeName]) {
console.warn(`No locale matching "${l}" found, using "en_us"`)
currentLocale = fallBackLocale
}
currentLocale = translations[localeName]
}
function localizeString(key, args = {}) {
key = key.toString().toLowerCase().replace(/[- ]/g, '_')
let rawTranslation = currentLocale[key] ?? fallBackLocale[key] ?? fallBackLocale['no_translation']
for (const replaceKey of Object.keys(args)) rawTranslation = rawTranslation.replaceAll(`{${replaceKey.toLowerCase()}}`, args[replaceKey])
return rawTranslation
}
module.exports = { setLocale, localizeString }