2022-11-07 00:56:44 +01:00
|
|
|
import Vue from "vue"
|
2022-11-09 00:10:08 +01:00
|
|
|
import enUsStrings from '../strings/en-us.json'
|
2022-11-07 00:56:44 +01:00
|
|
|
|
|
|
|
const defaultCode = 'en-us'
|
|
|
|
|
2022-11-08 01:27:17 +01:00
|
|
|
function supplant(str, subs) {
|
|
|
|
// source: http://crockford.com/javascript/remedial.html
|
|
|
|
return str.replace(/{([^{}]*)}/g,
|
|
|
|
function (a, b) {
|
|
|
|
var r = subs[b]
|
|
|
|
return typeof r === 'string' || typeof r === 'number' ? r : a
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-11-07 00:56:44 +01:00
|
|
|
Vue.prototype.$i18nCode = ''
|
2022-11-09 00:10:08 +01:00
|
|
|
Vue.prototype.$strings = enUsStrings
|
2022-11-08 01:27:17 +01:00
|
|
|
Vue.prototype.$getString = (key, subs) => {
|
|
|
|
if (!Vue.prototype.$strings[key]) return ''
|
|
|
|
if (subs && Array.isArray(subs) && subs.length) {
|
|
|
|
return supplant(Vue.prototype.$strings[key], subs)
|
|
|
|
}
|
|
|
|
return Vue.prototype.$strings[key]
|
|
|
|
}
|
2022-11-07 00:56:44 +01:00
|
|
|
|
2022-11-09 00:10:08 +01:00
|
|
|
var translations = {
|
|
|
|
[defaultCode]: enUsStrings
|
|
|
|
}
|
2022-11-07 00:56:44 +01:00
|
|
|
|
|
|
|
function loadTranslationStrings(code) {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
import(`../strings/${code}`).then((fileContents) => {
|
|
|
|
resolve(fileContents.default)
|
|
|
|
}).catch((error) => {
|
|
|
|
console.error('Failed to load i18n strings', code, error)
|
2022-11-09 00:10:08 +01:00
|
|
|
resolve(null)
|
2022-11-07 00:56:44 +01:00
|
|
|
})
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
async function loadi18n(code) {
|
|
|
|
if (Vue.prototype.$i18nCode == code) {
|
|
|
|
// already set
|
|
|
|
return
|
|
|
|
}
|
|
|
|
const strings = translations[code] || await loadTranslationStrings(code)
|
2022-11-09 00:10:08 +01:00
|
|
|
if (!strings) {
|
|
|
|
console.warn(`Invalid lang code ${code}`)
|
|
|
|
return
|
|
|
|
}
|
2022-11-07 00:56:44 +01:00
|
|
|
|
|
|
|
translations[code] = strings
|
|
|
|
Vue.prototype.$i18nCode = code
|
|
|
|
|
|
|
|
for (const key in Vue.prototype.$strings) {
|
|
|
|
Vue.prototype.$strings[key] = strings[key] || translations[defaultCode][key]
|
|
|
|
}
|
|
|
|
console.log('i18n strings=', Vue.prototype.$strings)
|
|
|
|
}
|
|
|
|
|
|
|
|
Vue.prototype.$i18nUpdate = loadi18n
|
|
|
|
|
2022-11-09 00:10:08 +01:00
|
|
|
const localLanguage = localStorage.getItem('lang')
|
|
|
|
if (localLanguage !== defaultCode) {
|
|
|
|
loadi18n(localLanguage)
|
|
|
|
}
|