From c76858ba3201f86588ef0f8f0b548036373f4573 Mon Sep 17 00:00:00 2001 From: ambar Date: Fri, 29 Mar 2024 15:55:35 +0800 Subject: [PATCH] feat: preserve query string when redirecting on first visit (#864) Co-authored-by: neverland --- .changeset/cyan-tigers-bow.md | 5 +++ .../src/logic/useRedirect4FirstVisit.ts | 31 ++++++++++--------- 2 files changed, 22 insertions(+), 14 deletions(-) create mode 100644 .changeset/cyan-tigers-bow.md diff --git a/.changeset/cyan-tigers-bow.md b/.changeset/cyan-tigers-bow.md new file mode 100644 index 000000000..8b8a5419c --- /dev/null +++ b/.changeset/cyan-tigers-bow.md @@ -0,0 +1,5 @@ +--- +"@rspress/theme-default": minor +--- + +feat: preserve query string when redirecting on first visit diff --git a/packages/theme-default/src/logic/useRedirect4FirstVisit.ts b/packages/theme-default/src/logic/useRedirect4FirstVisit.ts index d62ed31d4..b870f3b29 100644 --- a/packages/theme-default/src/logic/useRedirect4FirstVisit.ts +++ b/packages/theme-default/src/logic/useRedirect4FirstVisit.ts @@ -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'; @@ -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); } }, []); }