OSDN Git Service

Merge branch 'dashboardmaster' into dev
[bytom/bytom-electron.git] / modules / i18n.js
1 /**
2 The i18n module, loads the language files and initializes i18next
3
4 @module i18n
5 */
6 const i18n = require('i18next')
7 const extend = require('lodash/extend')
8
9 const LanguageDetector = require('i18next-browser-languagedetector')
10
11
12 const supported_languages = ['en', 'zh']
13
14 const resources = {
15   dev: { translations: require('./interface/i18n/desktop.en.i18n.json') },
16 }
17
18 // add supported languages
19 supported_languages.forEach((lang) => {
20   const desktopTranslations = require(`./interface/i18n/desktop.${lang}.i18n.json`)
21   const uiTranslations = require(`../src/locales/${lang}/translation.json`)
22   resources[lang] = { translations: extend(desktopTranslations, uiTranslations) }
23 })
24
25 /**
26 * Given a language code, get best matched code from supported languages.
27 *
28 * > getBestMatchedLangCode('en-US')
29 * 'en'
30 * > getBestMatchedLangCode('zh-TW')
31 * 'zh-TW'
32 * > getBestMatchedLangCode('no-such-code')
33 * 'en'
34 */
35 i18n.getBestMatchedLangCode = (langCode) => {
36   const codeList = Object.keys(resources)
37   let bestMatchedCode = langCode
38   if (codeList.indexOf(langCode) === -1) {
39     if (codeList.indexOf(langCode.substr(0, 2)) > -1) {
40       bestMatchedCode = langCode.substr(0, 2)
41     } else {
42       bestMatchedCode = 'en'
43     }
44   }
45   return bestMatchedCode
46 }
47
48 i18n.use(LanguageDetector).init({
49   lng:   global.language,
50   fallbackLng:  'en',
51   resources,
52   interpolation: {
53     escapeValue: false, // not needed for react!!
54     prefix: '__',
55     suffix: '__'
56   },
57   debug: false,
58
59   ns: ['translations'],
60   defaultNS: 'translations',
61
62   detection: {
63     // order and from where user language should be detected
64     order: ['localStorage', 'querystring', 'cookie',  'navigator', 'htmlTag', 'path', 'subdomain']
65   },
66
67   react: {
68     wait: true,
69     bindStore: false
70   }
71 })
72
73 module.exports = i18n