feat(theme): improve languages selector (#384)

This commit is contained in:
pengzhanbo 2024-12-22 00:10:06 +08:00 committed by GitHub
parent a21d9ed0b5
commit e9b6bce8e6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1,5 +1,5 @@
import { computed } from 'vue'
import { resolveRoute, useRouteLocale, withBase } from 'vuepress/client'
import { resolveRoute, useRouteLocale } from 'vuepress/client'
import { normalizeLink } from '../utils/index.js'
import { useData } from './data.js'
import { useBlogPageData } from './page.js'
@ -21,22 +21,31 @@ export function useLangs({
}
})
const getPageLink = (locale: string) => {
const filepath = page.value.filePathRelative
? `/${page.value.filePathRelative}`
: page.value.path
const pagePath = filepath.slice(routeLocale.value.length)
const targetPath = normalizeLink(locale, pagePath)
const resolvePath = (locale: string, url: string) => {
const targetPath = normalizeLink(locale, url.slice(routeLocale.value.length))
const { notFound, path } = resolveRoute(targetPath)
if (!notFound)
return notFound ? undefined : path
}
const getPageLink = (locale: string) => {
let path: string | undefined
// 尝试根据文件路径解析
if (page.value.filePathRelative) {
path = resolvePath(locale, `/${page.value.filePathRelative}`)
}
// 尝试根据路由路径解析
path ??= resolvePath(locale, page.value.path)
if (path)
return path
// fallback to blog
const blog = theme.value.blog
if (isBlogPost.value && blog !== false)
return withBase(blog?.link || normalizeLink(locale, 'blog/'))
return blog?.link || normalizeLink(locale, 'blog/')
const home = withBase(theme.value.home || '/')
const fallbackResolve = resolveRoute(withBase(locale))
// fallback to home
const home = theme.value.home || '/'
const fallbackResolve = resolveRoute(locale)
return fallbackResolve.notFound ? home : fallbackResolve.path
}