'use client'; import { useTheme } from '@/contexts/theme-context'; import { Sun, Moon, Monitor } from 'lucide-react'; import { useCallback, useState, useRef, useEffect } from 'react'; const THEME_OPTIONS = [ { value: 'light' as const, label: '浅色', icon: Sun }, { value: 'dark' as const, label: '深色', icon: Moon }, { value: 'system' as const, label: '跟随系统', icon: Monitor }, ]; export function ThemeToggle() { const { theme, setTheme } = useTheme(); const [open, setOpen] = useState(false); const ref = useRef(null); useEffect(() => { function handleClick(e: MouseEvent) { if (ref.current && !ref.current.contains(e.target as Node)) { setOpen(false); } } document.addEventListener('mousedown', handleClick); return () => document.removeEventListener('mousedown', handleClick); }, []); const handleSelect = useCallback( (value: 'light' | 'dark' | 'system') => { setTheme(value); setOpen(false); }, [setTheme], ); const CurrentIcon = THEME_OPTIONS.find((o) => o.value === theme)?.icon ?? Monitor; return (
{open && (
{THEME_OPTIONS.map((opt) => { const Icon = opt.icon; const isActive = theme === opt.value; return ( ); })}
)}
); }