FutureCloud/hooks/useLanguage.ts

50 lines
1.4 KiB
TypeScript
Raw Normal View History

2025-09-15 16:58:31 +08:00
// hooks/useLanguage.tsx
'use client';
import { useState, useEffect } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import { content, LanguageType, ContentType } from '../lib/content';
export function useLanguage(
initialLang: string
): {
currentLang: LanguageType;
setCurrentLang: (newLang: LanguageType) => void;
createLocalizedPath: (path: string) => string;
currentContent: ContentType;
} {
const router = useRouter();
const pathname = usePathname();
const SUPPORTED = ['en', 'zh-CN', 'zh-TW'] as const;
const normalized = (SUPPORTED.includes(initialLang as any)
? initialLang
: 'en') as LanguageType;
const [currentLang, setLang] = useState<LanguageType>(normalized);
useEffect(() => {
setLang(normalized);
}, [normalized]);
const setCurrentLang = (newLang: LanguageType) => {
const parts = pathname.split('/').filter(Boolean);
const rest = parts.slice(1).join('/');
router.push(`/${newLang}${rest ? '/' + rest : ''}`);
};
const createLocalizedPath = (path: string) =>
path.startsWith('/')
? `/${currentLang}${path}`
: `/${currentLang}/${path}`;
// —— 关键:从 content 里取出当前语言的数据 ——
const currentContent: ContentType = content[currentLang];
return {
currentLang,
setCurrentLang,
createLocalizedPath,
currentContent,
};
}