-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathi18n.js
More file actions
84 lines (68 loc) · 2.27 KB
/
i18n.js
File metadata and controls
84 lines (68 loc) · 2.27 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
79
80
81
82
83
84
import Vue from 'vue'
import Vuex from 'vuex'
import { debounce, isEmpty } from 'lodash'
import vuexI18n from 'vuex-i18n/dist/vuex-i18n.umd.js'
export default ({ app, env, req, cookie, store }) => {
const doDebug = env.NODE_ENV !== 'production'
const key = 'locale'
const changeHandler = debounce((mutation, store) => {
if (process.server) return
const currentLocale = app.$cookies.get(mutation.payload.locale)
const isDifferent = mutation.payload.locale !== currentLocale
if (isDifferent) {
app.$cookies.set(key, mutation.payload.locale)
}
const user = store.getters['auth/user']
const token = store.getters['auth/token']
// persist language if it differs from last value
if (isDifferent && user && user._id && token) {
store.dispatch('usersettings/patch', {
uiLanguage: mutation.payload.locale
}, { root: true })
}
}, 500)
const i18nStore = new Vuex.Store({
strict: doDebug
})
Vue.use(
vuexI18n.plugin,
i18nStore,
{
onTranslationNotFound: function (locale, key) {
console.warn(`vuex-i18n :: Key '${key}' not found for locale '${locale}'`)
}
})
// register the locales
Vue.i18n.add('en', require('~/locales/en.json'))
let userLocale = 'en'
const localeCookie = app.$cookies.get(key)
const userSettings = store.getters['auth/userSettings']
if (userSettings && userSettings.uiLanguage) {
// try to get saved user preference
userLocale = userSettings.uiLanguage
} else if (!isEmpty(localeCookie)) {
userLocale = localeCookie
} else {
userLocale = process.browser ? (navigator.language || navigator.userLanguage) : req.locale
if (userLocale && !isEmpty(userLocale.language)) {
userLocale = userLocale.language.substr(0, 2)
}
}
const availableLocales = ['de', 'en']
const locale = (availableLocales.indexOf(userLocale) >= 0) ? userLocale : 'en'
if (locale !== 'en') {
Vue.i18n.add(locale, require(`~/locales/${locale}.json`))
}
// Set the start locale to use
Vue.i18n.set(locale)
Vue.i18n.fallback('en')
if (process.client) {
i18nStore.subscribe((mutation, s) => {
if (mutation.type === 'i18n/SET_LOCALE') {
changeHandler(mutation, store)
}
})
}
app.$i18n = Vue.i18n
return i18nStore
}