Skip to content

Commit

Permalink
feat: preserve query string when redirecting on first visit (web-infr…
Browse files Browse the repository at this point in the history
…a-dev#864)

Co-authored-by: neverland <[email protected]>
  • Loading branch information
2 people authored and Timeless0911 committed Mar 29, 2024
1 parent 5db1516 commit c76858b
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
5 changes: 5 additions & 0 deletions .changeset/cyan-tigers-bow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@rspress/theme-default": minor
---

feat: preserve query string when redirecting on first visit
31 changes: 17 additions & 14 deletions packages/theme-default/src/logic/useRedirect4FirstVisit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function useRedirect4FirstVisit() {
return;
}
// Normalize current url, to ensure that the home url is always with a trailing slash
const { pathname } = window.location;
const { pathname, search } = window.location;
const cleanPathname = removeBase(pathname);
// Check if the user is visiting the site for the first time
const FIRST_VISIT_KEY = 'rspress-visited';
Expand All @@ -37,19 +37,22 @@ export function useRedirect4FirstVisit() {
if (!langs.includes(targetLang)) {
return;
}
if (targetLang !== currentLang) {
if (targetLang === defaultLang) {
// Redirect to the default language
window.location.replace(pathname.replace(`/${currentLang}`, ''));
} else if (currentLang === defaultLang) {
// Redirect to the current language
window.location.replace(withBase(`/${targetLang}${cleanPathname}`));
} else {
// Redirect to the current language
window.location.replace(
pathname.replace(`/${currentLang}`, `/${targetLang}`),
);
}
if (targetLang === currentLang) {
return;
}
let newPath: string;
if (targetLang === defaultLang) {
// Redirect to the default language
newPath = pathname.replace(`/${currentLang}`, '');
} else if (currentLang === defaultLang) {
// Redirect to the current language
newPath = withBase(`/${targetLang}${cleanPathname}`);
} else {
// Redirect to the current language
newPath = pathname.replace(`/${currentLang}`, `/${targetLang}`);
}
if (newPath) {
window.location.replace(newPath + search);
}
}, []);
}

0 comments on commit c76858b

Please sign in to comment.