From a61b299b513af15ed93318fae920f5185d1a9327 Mon Sep 17 00:00:00 2001 From: radishzzz Date: Sat, 15 Mar 2025 12:36:02 +0000 Subject: [PATCH] fix: optimize the language switching order on the article page --- src/i18n/path.ts | 17 ++++++++++++----- src/pages/[...posts_slug].astro | 8 ++++++++ 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/src/i18n/path.ts b/src/i18n/path.ts index ddfa435..6a8b4c4 100644 --- a/src/i18n/path.ts +++ b/src/i18n/path.ts @@ -1,4 +1,4 @@ -import { defaultLocale } from '@/config' +import { defaultLocale, moreLocales } from '@/config' import { getLangFromPath, getNextLang } from '@/i18n/lang' import { cleanPath } from '@/utils/page' @@ -84,19 +84,26 @@ export function getPostNextLangUrl(currentPath: string, supportedLangs: string[] return getNextLangUrl(currentPath) } + // 确保supportedLangs按照allLocales的顺序排序 + const sortedLangs = [...supportedLangs].sort((a, b) => { + // 使用导入的allLocales变量 + const allLocales = [defaultLocale, ...moreLocales] + return allLocales.indexOf(a) - allLocales.indexOf(b) + }) + // 找到当前语言在支持的语言中的索引 - const currentIndex = supportedLangs.indexOf(currentLang) + const currentIndex = sortedLangs.indexOf(currentLang) // 如果当前语言不在支持的语言中,或者路径是根路径,返回第一个支持的语言 if (currentIndex === -1 || currentPath === '/') { - const nextLang = supportedLangs[0] + const nextLang = sortedLangs[0] // 如果下一个语言是默认语言,返回根路径 return nextLang === defaultLocale ? '/' : `/${nextLang}/` } // 计算下一个语言的索引 - const nextIndex = (currentIndex + 1) % supportedLangs.length - const nextLang = supportedLangs[nextIndex] + const nextIndex = (currentIndex + 1) % sortedLangs.length + const nextLang = sortedLangs[nextIndex] // 构建下一个语言的URL return buildNextLangUrl(currentPath, currentLang, nextLang) diff --git a/src/pages/[...posts_slug].astro b/src/pages/[...posts_slug].astro index fe5a6e2..0b7a605 100644 --- a/src/pages/[...posts_slug].astro +++ b/src/pages/[...posts_slug].astro @@ -38,6 +38,14 @@ export async function getStaticPaths() { } }) + // 对每个文章的supportedLangs按照allLocales的顺序排序 + Object.keys(slugToLangs).forEach((slug) => { + // 按照allLocales的顺序排序 + slugToLangs[slug].sort((a, b) => { + return allLocales.indexOf(a) - allLocales.indexOf(b) + }) + }) + // 定义路径数组的类型 type PathItem = { params: { posts_slug: string }