This commit is contained in:
hailin 2025-04-17 09:44:39 +08:00
parent a5a97137f6
commit 5b4116dfe7
3 changed files with 47 additions and 1 deletions

View File

@ -5,6 +5,9 @@ import { IconArrowRight } from "@tabler/icons-react"
import { useTheme } from "next-themes"
import Link from "next/link"
import HomeRedirector from "@/components/utility/home-redirector"
import { LanguageSwitcher } from '@/components/ui/language-switcher'
export default function HomePage() {
@ -13,6 +16,7 @@ export default function HomePage() {
return (
<div className="flex size-full flex-col items-center justify-center relative">
<HomeRedirector />
<LanguageSwitcher />
<div>

View File

@ -2,7 +2,7 @@
import i18nConfig from '@/i18nConfig'
import { usePathname, useRouter } from 'next/navigation'
import { useTransition } from 'react'
import { useEffect, useTransition } from 'react'
import { Globe } from 'lucide-react'
export function LanguageSwitcher() {
@ -12,8 +12,25 @@ export function LanguageSwitcher() {
const currentLocale = pathname.split('/')[1] || i18nConfig.defaultLocale
useEffect(() => {
// 第一次访问页面时,如果 URL 有语言,就记住
if (typeof window !== 'undefined') {
const saved = localStorage.getItem('preferred-language')
if (!saved || saved !== currentLocale) {
localStorage.setItem('preferred-language', currentLocale)
}
}
}, [currentLocale])
const handleChange = (e: React.ChangeEvent<HTMLSelectElement>) => {
const newLocale = e.target.value
// 保存用户选择
if (typeof window !== 'undefined') {
localStorage.setItem('preferred-language', newLocale)
}
// 替换语言部分的路径
const segments = pathname.split('/')
segments[1] = newLocale
const newPath = segments.join('/')

View File

@ -0,0 +1,25 @@
'use client'
import { useEffect } from 'react'
import { useRouter } from 'next/navigation'
import i18nConfig from '@/i18nConfig'
export default function HomeRedirector() {
const router = useRouter()
useEffect(() => {
const preferred = localStorage.getItem('preferred-language')
const currentPath = window.location.pathname
if (
preferred &&
i18nConfig.locales.includes(preferred) &&
!currentPath.startsWith(`/${preferred}/`)
) {
const newPath = `/${preferred}${currentPath}`
router.replace(newPath)
}
}, [])
return null
}