'use client'; import { Moon, Sun } from 'lucide-react'; import { useTheme } from 'next-themes'; import { useEffect, useState } from 'react'; export function ThemeToggle() { const [mounted, setMounted] = useState(false); const { setTheme, resolvedTheme } = useTheme(); const setThemeColor = (theme?: string) => { const meta = document.querySelector('meta[name="theme-color"]'); if (!meta) { const meta = document.createElement('meta'); meta.name = 'theme-color'; meta.content = theme === 'dark' ? '#0c111c' : '#f9fbfe'; document.head.appendChild(meta); } else { meta.setAttribute('content', theme === 'dark' ? '#0c111c' : '#f9fbfe'); } }; useEffect(() => { setMounted(true); setThemeColor(resolvedTheme); }, [resolvedTheme]); if (!mounted) { // 渲染一个占位符以避免布局偏移 return
; } const toggleTheme = () => { // 检查浏览器是否支持 View Transitions API const targetTheme = resolvedTheme === 'dark' ? 'light' : 'dark'; setThemeColor(targetTheme); // 使用更好的类型定义 const documentWithTransition = document as Document & { startViewTransition?: (callback: () => void) => void; }; if (!documentWithTransition.startViewTransition) { setTheme(targetTheme); return; } documentWithTransition.startViewTransition(() => { setTheme(targetTheme); }); }; return ( ); }