feat(i18n): use preferred language when users first visit (#263)

This commit is contained in:
Alex 2022-12-02 10:17:41 +08:00 committed by GitHub
parent 75d1a39017
commit 0f7de38c24
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -24,11 +24,19 @@ export function setupPageHeader() {
}
export async function setupI18n() {
// TODO: guess user language
const { locale, setLocale } = useI18n()
const { locale, setLocale, locales } = useI18n()
const isFirstVisit = !window.localStorage.getItem(STORAGE_KEY_LANG)
const localeStorage = useLocalStorage(STORAGE_KEY_LANG, locale.value)
if (isFirstVisit) {
const userLang = (navigator.language || 'en-US').toLowerCase()
// cause vue-i18n not explicit export LocaleObject type
const supportLocales = unref(locales) as { code: string }[]
const lang = supportLocales.find(locale => userLang.startsWith(locale.code.toLowerCase()))?.code
|| supportLocales.find(locale => userLang.startsWith(locale.code.split('-')[0]))?.code
localeStorage.value = lang || 'en-US'
}
if (localeStorage.value !== locale.value)
await setLocale(localeStorage.value)