translation.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import { computed } from 'vue'
  2. import { useRoute, useRouter } from 'vitepress'
  3. import { isClient, useStorage } from '@vueuse/core'
  4. import { PREFERRED_LANG_KEY } from '../constant'
  5. import langs from '../../i18n/lang.json'
  6. import translationLocale from '../../i18n/component/translation.json'
  7. import { useLang } from './lang'
  8. export const useTranslation = () => {
  9. const route = useRoute()
  10. const router = useRouter()
  11. const lang = useLang()
  12. const languageMap = {
  13. 'en-US': 'English',
  14. 'zh-CN': '中文',
  15. 'es-ES': 'Español',
  16. 'fr-FR': 'Français',
  17. 'ja-JP': '日本語',
  18. }
  19. const helpTranslate = computed(() => translationLocale[lang.value].help)
  20. const langsRef = computed(() => {
  21. const currentLang = lang.value
  22. // When there is no zh-CN in the list, meaning this is the PR preview
  23. // so we simply return the current list which contains only en-US
  24. if (!langs.includes('zh-CN')) return []
  25. const langsCopy = langs.slice(0)
  26. langsCopy.splice(langsCopy.indexOf(currentLang), 1)
  27. // if current language is not zh-CN, then zh-CN needs to be moved to the head.
  28. if (currentLang !== 'zh-CN') {
  29. langsCopy.splice(langsCopy.indexOf('zh-CN'), 1)
  30. }
  31. return currentLang === 'zh-CN' ? langsCopy : ['zh-CN'].concat(langsCopy)
  32. })
  33. const language = useStorage(PREFERRED_LANG_KEY, 'en-US')
  34. const switchLang = (targetLang: string) => {
  35. if (lang.value === targetLang) return
  36. language.value = targetLang
  37. const firstSlash = route.path.indexOf('/', 1)
  38. const goTo = `/${targetLang}/${route.path.slice(firstSlash + 1)}`
  39. router.go(goTo)
  40. if (isClient) {
  41. navigator?.serviceWorker.controller?.postMessage({
  42. type: 'LANG',
  43. lang: targetLang,
  44. })
  45. }
  46. }
  47. return {
  48. helpTranslate,
  49. languageMap,
  50. langs: langsRef,
  51. lang,
  52. switchLang,
  53. }
  54. }