-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathmodule.js
101 lines (98 loc) · 2.86 KB
/
module.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
import { setLocale, setTranslations } from './t';
import farm from '../farmClient';
const enabledLocales = [
{
code: 'pt',
aliases: ['pt-br', 'pt-pt'],
language: 'pt',
name: 'Portuguese, International',
native: 'Português, Internacional',
},
{
code: 'de',
aliases: ['de-de', 'de-at'],
language: 'de',
name: 'German',
native: 'Deutsch',
},
];
const getCode = locale => enabledLocales.find(l => (
l.code === locale || l.aliases.includes(locale)
))?.code;
export default {
state: {
locale: 'en',
languages: [],
},
mutations: {
setLocale(state, locale) {
const code = getCode(locale) || 'en';
state.locale = code;
setLocale(code);
localStorage.setItem('locale', code);
if (locale !== 'en' && !getCode(locale)) {
// eslint-disable-next-line no-console
console.warn(`No translation provided for language code ${locale}.`);
}
},
setLanguages(state, langs) {
state.languages = langs;
},
},
actions: {
updateLanguages({ commit }, response) {
const token = JSON.parse(localStorage.getItem('token'));
const setLangs = (res) => {
const locale = res.user?.language;
if (locale) {
commit('setLocale', locale);
}
const langs = Object.values(res?.languages || {})
.reduce((ls, lang, i, arr) => {
const code = getCode(lang.language);
if (code && code === lang.language) {
return ls.concat(lang);
}
if (code && !arr.some(l => l.language === lang.language)) {
return ls.concat(enabledLocales.find(l => l.code === code));
}
return ls;
}, []);
commit('setLanguages', langs);
localStorage.setItem('languages', JSON.stringify(langs));
langs.forEach(({ language }) => {
const code = getCode(language);
import(/* webpackChunkName: "l10n" */ `./translations/${code}.js`)
.then(({ default: translations }) => {
setTranslations(code, translations);
});
});
return res;
};
if (response) {
return setLangs(response);
}
if (token) {
return farm().info().then(setLangs);
}
return null;
},
loadCachedLanguages({ commit }) {
const locale = localStorage.getItem('locale');
if (locale) {
commit('setLocale', locale);
}
const langs = JSON.parse(localStorage.getItem('languages'));
if (langs) {
commit('setLanguages', langs);
langs.forEach(({ language }) => {
const code = getCode(language);
import(/* webpackChunkName: "l10n" */ `./translations/${code}.js`)
.then(({ default: translations }) => {
setTranslations(code, translations);
});
});
}
},
},
};