mirror of
https://gitee.com/element-plus/element-plus.git
synced 2024-12-15 09:50:58 +08:00
0c92e8a8d2
* docs: cache the preferred lang pages in the PWA * chore: remove index.html in manifest * fix: no cache the '/' page * perf: optimize code * docs: add always refresh from PWA
70 lines
1.8 KiB
TypeScript
70 lines
1.8 KiB
TypeScript
import { computed } from 'vue'
|
|
import { useRoute, useRouter } from 'vitepress'
|
|
import { isClient, useStorage } from '@vueuse/core'
|
|
import { PREFERRED_LANG_KEY } from '../constant'
|
|
|
|
import langs from '../../i18n/lang.json'
|
|
import translationLocale from '../../i18n/component/translation.json'
|
|
import { useLang } from './lang'
|
|
|
|
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)
|
|
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
|
|
if (!langs.includes('zh-CN')) return []
|
|
const langsCopy = langs.slice(0)
|
|
langsCopy.splice(langsCopy.indexOf(currentLang), 1)
|
|
|
|
// 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)
|
|
}
|
|
|
|
return currentLang === 'zh-CN' ? langsCopy : ['zh-CN'].concat(langsCopy)
|
|
})
|
|
|
|
const language = useStorage(PREFERRED_LANG_KEY, 'en-US')
|
|
|
|
const switchLang = (targetLang: string) => {
|
|
if (lang.value === targetLang) return
|
|
|
|
language.value = targetLang
|
|
|
|
const firstSlash = route.path.indexOf('/', 1)
|
|
|
|
const goTo = `/${targetLang}/${route.path.slice(firstSlash + 1)}`
|
|
|
|
router.go(goTo)
|
|
|
|
if (isClient) {
|
|
navigator?.serviceWorker.controller?.postMessage({
|
|
type: 'LANG',
|
|
lang: targetLang,
|
|
})
|
|
}
|
|
}
|
|
|
|
return {
|
|
helpTranslate,
|
|
languageMap,
|
|
langs: langsRef,
|
|
lang,
|
|
switchLang,
|
|
}
|
|
}
|