test: language switcher and i18n refactor

This commit is contained in:
radishzzz 2025-03-14 00:51:54 +00:00
parent 19d7ba4905
commit 4651828dd1
10 changed files with 127 additions and 133 deletions

60
src/utils/i18n/path.ts Normal file
View file

@ -0,0 +1,60 @@
import themeConfig from '@/config'
const defaultLocale = themeConfig.global.locale
const moreLocales = themeConfig.global.moreLocale
export function cleanPath(path: string) {
return path.replace(/^\/|\/$/g, '')
}
export function getLangFromPath(path: string) {
const secondaryLang = moreLocales.find(
lang =>
path.startsWith(`/${lang}/`),
)
return secondaryLang || defaultLocale
}
export function getLocalizedPath(path: string, currentLang?: string) {
const clean = cleanPath(path)
const lang = currentLang || getLangFromPath(path)
if (clean === '') {
return lang === defaultLocale ? '/' : `/${lang}/`
}
return lang === defaultLocale ? `/${clean}/` : `/${lang}/${clean}/`
}
export function isHomePage(path: string) {
const clean = cleanPath(path)
return clean === '' || moreLocales.includes(clean)
}
export function isPostPage(path: string) {
const clean = cleanPath(path)
return clean.startsWith('posts') || moreLocales.some(lang => clean.startsWith(`${lang}/posts`))
}
export function isTagPage(path: string) {
const clean = cleanPath(path)
return clean.startsWith('tags') || moreLocales.some(lang => clean.startsWith(`${lang}/tags`))
}
export function isAboutPage(path: string) {
const clean = cleanPath(path)
return clean.startsWith('about') || moreLocales.some(lang => clean.startsWith(`${lang}/about`))
}
export function getPagePath(path: string) {
const currentLang = getLangFromPath(path)
return {
currentLang,
isHome: isHomePage(path),
isPost: isPostPage(path),
isTag: isTagPage(path),
isAbout: isAboutPage(path),
getLocalizedPath: (targetPath: string) => getLocalizedPath(targetPath, currentLang),
}
}