HaoAws/components/LanguageSwitcher.tsx
2025-09-16 16:37:48 +08:00

72 lines
2.5 KiB
TypeScript

'use client';
import { Locale, languages, generateLocalizedPath } from '@/lib/i18n';
interface LanguageSwitcherProps {
currentLocale: Locale;
availableLocales: Locale[];
articleId: string;
}
export default function LanguageSwitcher({
currentLocale,
availableLocales,
articleId
}: LanguageSwitcherProps) {
const handleLanguageChange = (newLocale: Locale) => {
// Set locale cookie
document.cookie = `locale=${newLocale}; path=/; max-age=31536000`; // 1 year
// Navigate to the new path
const newPath = generateLocalizedPath(`news/${articleId}`, newLocale);
window.location.href = newPath;
};
return (
<div className="flex space-x-2">
{languages.map((lang) => {
const isAvailable = availableLocales.includes(lang.code);
const isCurrent = lang.code === currentLocale;
if (!isAvailable) {
return (
<span
key={lang.code}
className="px-3 py-1 text-sm bg-gray-100 text-gray-400 rounded-full cursor-not-allowed"
title={
currentLocale === 'en'
? 'Translation not available'
: currentLocale === 'zh-TW'
? '翻譯不可用'
: '翻译不可用'
}
>
{lang.flag} {lang.name}
</span>
);
}
if (isCurrent) {
return (
<span
key={lang.code}
className="px-3 py-1 text-sm bg-blue-600 text-white rounded-full"
>
{lang.flag} {lang.name}
</span>
);
}
return (
<button
key={lang.code}
onClick={() => handleLanguageChange(lang.code)}
className="px-3 py-1 text-sm bg-gray-100 text-gray-700 hover:bg-gray-200 rounded-full transition-colors cursor-pointer"
>
{lang.flag} {lang.name}
</button>
);
})}
</div>
);
}