Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: preserve query string when redirecting on first visit #864

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -18,7 +18,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 @@ -33,19 +33,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);
}
}, []);
}
Loading