fix language switch

This commit is contained in:
songtianlun 2025-08-01 22:34:06 +08:00
parent 10dc89ab68
commit 315ee14087
2 changed files with 17 additions and 11 deletions

View File

@ -33,11 +33,14 @@ export function LanguageToggle({ variant = 'dropdown', showLabel = true }: Langu
}, []) }, [])
const changeLanguage = (locale: string) => { const changeLanguage = (locale: string) => {
// Set cookie // Clear existing locale cookie first
document.cookie = `locale=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; samesite=lax`
// Set new locale cookie
document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax` document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`
// Reload page to apply new locale // Force reload to apply new locale
window.location.reload() window.location.href = window.location.href
} }
if (variant === 'button') { if (variant === 'button') {
@ -122,11 +125,14 @@ export function MobileLanguageToggle() {
}, []) }, [])
const changeLanguage = (locale: string) => { const changeLanguage = (locale: string) => {
// Set cookie // Clear existing locale cookie first
document.cookie = `locale=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; samesite=lax`
// Set new locale cookie
document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax` document.cookie = `locale=${locale}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`
// Reload page to apply new locale // Force reload to apply new locale
window.location.reload() window.location.href = window.location.href
} }
return ( return (

View File

@ -42,20 +42,20 @@ export default getRequestConfig(async () => {
let locale: Locale = defaultLocale; let locale: Locale = defaultLocale;
// Parse locale from cookies // Parse locale from cookies first (user preference takes priority)
if (cookieHeader) { if (cookieHeader) {
const cookies = cookieHeader.split(';'); const cookies = cookieHeader.split(';');
const localeCookie = cookies.find(cookie => cookie.trim().startsWith('locale=')); const localeCookie = cookies.find(cookie => cookie.trim().startsWith('locale='));
if (localeCookie) { if (localeCookie) {
const localeValue = localeCookie.split('=')[1]; const localeValue = localeCookie.split('=')[1]?.trim();
if (locales.includes(localeValue as Locale)) { if (localeValue && locales.includes(localeValue as Locale)) {
locale = localeValue as Locale; locale = localeValue as Locale;
} }
} }
} }
// If no locale found in cookies, detect from headers // Only detect from headers if no valid cookie found
if (locale === defaultLocale) { if (!cookieHeader || !cookieHeader.includes('locale=')) {
locale = await getLocaleFromHeaders(); locale = await getLocaleFromHeaders();
} }