69 lines
1.9 KiB
TypeScript
69 lines
1.9 KiB
TypeScript
'use client'
|
|
|
|
import i18nConfig from '@/i18nConfig'
|
|
import { usePathname, useRouter } from 'next/navigation'
|
|
import { useEffect, useTransition } from 'react'
|
|
import { Globe } from 'lucide-react'
|
|
|
|
export function LanguageSwitcher() {
|
|
const router = useRouter()
|
|
const pathname = usePathname()
|
|
const [isPending, startTransition] = useTransition()
|
|
|
|
const currentLocale = pathname.split('/')[1] || i18nConfig.defaultLocale
|
|
|
|
useEffect(() => {
|
|
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('/')
|
|
|
|
// ✅ 修复:类型断言 readonly -> string[]
|
|
const localeList = [...i18nConfig.locales] as string[]
|
|
const isLocaleInPath = localeList.includes(segments[1])
|
|
|
|
if (isLocaleInPath) {
|
|
segments[1] = newLocale
|
|
} else {
|
|
segments.unshift(newLocale)
|
|
}
|
|
|
|
const newPath = segments.join('/')
|
|
|
|
startTransition(() => {
|
|
router.push(newPath)
|
|
router.refresh()
|
|
})
|
|
}
|
|
|
|
return (
|
|
<div className="absolute top-4 right-4 z-50 flex items-center gap-2">
|
|
<Globe size={18} className="text-muted-foreground" />
|
|
<select
|
|
className="rounded-md border px-2 py-1 text-sm bg-background text-foreground"
|
|
value={currentLocale}
|
|
onChange={handleChange}
|
|
disabled={isPending}
|
|
>
|
|
{i18nConfig.locales.map(locale => (
|
|
<option key={locale} value={locale}>
|
|
{i18nConfig.languageNames[locale] || locale.toUpperCase()}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
)
|
|
}
|