forked from samuelmeuli/mini-diary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i18n.js
84 lines (74 loc) · 2.41 KB
/
i18n.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
const { app } = require('electron');
const translationsDe = require('./translations/de');
const translationsEn = require('./translations/en');
const translationsEs = require('./translations/es');
const translationsFr = require('./translations/fr');
const translationsIs = require('./translations/is');
const translationsPt = require('./translations/pt');
const translationsTr = require('./translations/tr');
const ALL_TRANSLATIONS = {
de: translationsDe,
en: translationsEn,
es: translationsEs,
fr: translationsFr,
is: translationsIs,
pt: translationsPt,
tr: translationsTr
};
const DEFAULT_LANG = 'en';
const systemLang = app.getLocale();
let lang; // Language used by app (e.g. 'en-US'), used for dates/calendar
let langNoRegion; // Language used by app without region string (e.g. 'en'), used for translations
let translations; // String translations for langNoRegion
/**
* Determine language to use for the app (use system language if translations are available,
* otherwise fall back to default language
*/
function setUsedLang() {
const systemLangNoRegion = systemLang.split('-')[0];
const defaultTranslations = ALL_TRANSLATIONS[DEFAULT_LANG];
if (systemLangNoRegion in ALL_TRANSLATIONS) {
// Use system language if translations are available
lang = systemLang;
langNoRegion = systemLangNoRegion;
translations = {
...defaultTranslations,
...ALL_TRANSLATIONS[langNoRegion]
};
} else {
// Otherwise, fall back to default language
lang = DEFAULT_LANG;
langNoRegion = DEFAULT_LANG;
translations = defaultTranslations;
}
}
/**
* Return translation for string with the provided translation key. Perform string substitutions if
* required
*/
function translate(i18nKey, substitutions) {
if (!(i18nKey in translations)) {
console.error(`Missing translation of i18nKey "${i18nKey}"`);
return i18nKey;
}
// Return translation if no `substitutions` object is provided
let translation = translations[i18nKey];
if (!substitutions) {
return translation;
}
// Perform string substitutions if `substitutions` object is provided
// Example:
// Translation definition: { test: 'Hello {var}' }
// Function call: translate('test', { var: 'World' })
// Result: 'Hello World'
Object.entries(substitutions).forEach(([toReplace, replacement]) => {
translation = translation.replace(`{${toReplace}}`, replacement);
});
return translation;
}
setUsedLang();
module.exports = {
lang,
translate,
translations
};