2023-01-12 20:52:52 +03:00
|
|
|
import type { VueI18n } from 'vue-i18n'
|
|
|
|
import type { LocaleObject } from 'vue-i18n-routing'
|
2023-01-14 12:34:53 +03:00
|
|
|
import { DEFAULT_LANGUAGE } from '~/constants'
|
2022-12-28 06:50:29 +03:00
|
|
|
|
|
|
|
export default defineNuxtPlugin(async (nuxt) => {
|
2023-01-12 20:52:52 +03:00
|
|
|
const i18n = nuxt.vueApp.config.globalProperties.$i18n as VueI18n
|
|
|
|
const { setLocale, locales } = i18n
|
|
|
|
const supportLanguages = (locales as LocaleObject[]).map(locale => locale.code)
|
|
|
|
const userSettings = useUserSettings()
|
2022-12-28 06:50:29 +03:00
|
|
|
|
2023-01-12 20:52:52 +03:00
|
|
|
if (process.server) {
|
|
|
|
const headers = useRequestHeaders()
|
|
|
|
|
2023-01-14 12:34:53 +03:00
|
|
|
let lang = userSettings.value.language
|
2023-01-12 20:52:52 +03:00
|
|
|
if (!lang || !supportLanguages.includes(lang)) {
|
|
|
|
// first visit
|
|
|
|
if (headers['accept-language']) {
|
|
|
|
// detect language from header
|
|
|
|
const userLanguages = headers['accept-language'].split(',').map(lang => lang.split(';')[0].toLowerCase())
|
|
|
|
lang = matchLanguages(supportLanguages, userLanguages) || DEFAULT_LANGUAGE
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
lang = DEFAULT_LANGUAGE
|
|
|
|
}
|
|
|
|
}
|
2022-12-28 06:50:29 +03:00
|
|
|
|
2023-01-12 20:52:52 +03:00
|
|
|
if (lang !== i18n.locale)
|
2023-01-14 12:34:53 +03:00
|
|
|
await setLocale(userSettings.value.language)
|
2022-12-28 06:50:29 +03:00
|
|
|
|
2023-01-12 20:52:52 +03:00
|
|
|
return
|
2022-12-28 06:50:29 +03:00
|
|
|
}
|
2023-01-12 20:52:52 +03:00
|
|
|
|
|
|
|
// could be null if browser don't accept cookie
|
2023-01-14 12:34:53 +03:00
|
|
|
if (!userSettings.value.language || !supportLanguages.includes(userSettings.value.language))
|
|
|
|
userSettings.value.language = DEFAULT_LANGUAGE
|
2023-01-12 20:52:52 +03:00
|
|
|
|
|
|
|
watch(() => userSettings.value.language, (lang) => {
|
|
|
|
if (lang !== i18n.locale)
|
|
|
|
setLocale(lang)
|
|
|
|
}, { immediate: true })
|
2022-12-28 06:50:29 +03:00
|
|
|
})
|