fix(i18n): improve language path handling and prevent unnecessary redirects

- Fix edge cases in path processing for language switching
- Add checks to prevent redirects to the same page
- Update documentation to reflect current project structure
This commit is contained in:
joyzhao
2025-06-19 10:13:49 +08:00
parent 7bb617a5c5
commit 4621223d26
3 changed files with 60 additions and 45 deletions

View File

@@ -40,8 +40,10 @@ export default function LanguageSwitcher({ lang: initialLang }: LanguageSwitcher
// Check if the first part of the path is a known language code
if (currentPathParts.length > 0 && Object.keys(i18nLanguages).includes(currentPathParts[0])) {
// If the first part is a language code, remove it to get the base path
basePath = '/' + currentPathParts.slice(1).join('/');
} else {
// If no language code in path, use the current path as base
basePath = currentPathname;
}
@@ -49,7 +51,9 @@ export default function LanguageSwitcher({ lang: initialLang }: LanguageSwitcher
if (!basePath.startsWith('/')) {
basePath = '/' + basePath;
}
// Fix for empty paths
if (basePath === '//') basePath = '/';
if (basePath === '') basePath = '/';
let newPath;
// If the target language is the default language and prefixDefaultLocale is false (as per our astro.config.mjs)
@@ -63,9 +67,13 @@ export default function LanguageSwitcher({ lang: initialLang }: LanguageSwitcher
// Clean up double slashes, just in case
newPath = newPath.replace(/\/\/+/g, '/');
if (newPath === '') newPath = '/'; // Handle case where basePath might be empty resulting in just /zh or /en
window.location.href = newPath;
// Handle case where basePath might be empty resulting in just /zh or /en
if (newPath === '') newPath = '/';
// Prevent unnecessary redirects to the same page
if (newPath !== currentPathname) {
window.location.href = newPath;
}
}
};