2021-09-17 00:18:50 +08:00
|
|
|
import { computed } from 'vue'
|
2022-03-25 15:35:56 +08:00
|
|
|
import { useRoute, useRouter } from 'vitepress'
|
2022-03-15 22:13:01 +08:00
|
|
|
import { useStorage } from '@vueuse/core'
|
2021-09-17 00:18:50 +08:00
|
|
|
import { PREFERRED_LANG_KEY } from '../constant'
|
|
|
|
|
|
|
|
import langs from '../../i18n/lang.json'
|
|
|
|
import translationLocale from '../../i18n/component/translation.json'
|
2021-09-23 14:16:37 +08:00
|
|
|
import { useLang } from './lang'
|
2021-09-17 00:18:50 +08:00
|
|
|
|
|
|
|
export const useTranslation = () => {
|
|
|
|
const route = useRoute()
|
|
|
|
const router = useRouter()
|
|
|
|
const lang = useLang()
|
|
|
|
|
|
|
|
const languageMap = {
|
|
|
|
'en-US': 'English',
|
|
|
|
'zh-CN': '中文',
|
|
|
|
'es-ES': 'Español',
|
|
|
|
'fr-FR': 'Français',
|
|
|
|
'ja-JP': '日本語',
|
|
|
|
}
|
|
|
|
|
|
|
|
const helpTranslate = computed(() => translationLocale[lang.value].help)
|
2021-10-22 14:50:30 +08:00
|
|
|
const langsRef = computed(() => {
|
|
|
|
const currentLang = lang.value
|
|
|
|
|
|
|
|
// When there is no zh-CN in the list, meaning this is the PR preview
|
|
|
|
// so we simply return the current list which contains only en-US
|
2021-10-22 22:50:54 +08:00
|
|
|
if (!langs.includes('zh-CN')) return []
|
2021-10-22 14:50:30 +08:00
|
|
|
const langsCopy = langs.slice(0)
|
|
|
|
langsCopy.splice(langsCopy.indexOf(currentLang), 1)
|
|
|
|
|
2021-10-23 01:23:49 +08:00
|
|
|
// if current language is not zh-CN, then zh-CN needs to be moved to the head.
|
|
|
|
if (currentLang !== 'zh-CN') {
|
|
|
|
langsCopy.splice(langsCopy.indexOf('zh-CN'), 1)
|
|
|
|
}
|
|
|
|
|
2021-10-22 14:50:30 +08:00
|
|
|
return currentLang === 'zh-CN' ? langsCopy : ['zh-CN'].concat(langsCopy)
|
|
|
|
})
|
2021-09-17 00:18:50 +08:00
|
|
|
|
2022-03-15 22:13:01 +08:00
|
|
|
const language = useStorage(PREFERRED_LANG_KEY, 'en-US')
|
|
|
|
|
2021-09-17 00:18:50 +08:00
|
|
|
const switchLang = (targetLang: string) => {
|
|
|
|
if (lang.value === targetLang) return
|
2022-03-15 22:13:01 +08:00
|
|
|
|
|
|
|
language.value = targetLang
|
|
|
|
|
2021-09-17 00:18:50 +08:00
|
|
|
const firstSlash = route.path.indexOf('/', 1)
|
|
|
|
|
|
|
|
const goTo = `/${targetLang}/${route.path.slice(firstSlash + 1)}`
|
|
|
|
|
|
|
|
router.go(goTo)
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
helpTranslate,
|
|
|
|
languageMap,
|
2021-10-22 14:50:30 +08:00
|
|
|
langs: langsRef,
|
2021-09-17 00:18:50 +08:00
|
|
|
lang,
|
|
|
|
switchLang,
|
|
|
|
}
|
|
|
|
}
|