From 0f7de38c2414f3fc41008f3d60b52428b603703b Mon Sep 17 00:00:00 2001 From: Alex <49969959+alexzhang1030@users.noreply.github.com> Date: Fri, 2 Dec 2022 10:17:41 +0800 Subject: [PATCH] feat(i18n): use preferred language when users first visit (#263) --- composables/setups.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/composables/setups.ts b/composables/setups.ts index dab9581e..367e43e6 100644 --- a/composables/setups.ts +++ b/composables/setups.ts @@ -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)