mirror of
https://github.com/MoonTechLab/LunaTV.git
synced 2026-02-24 04:04:43 +08:00
feat: dark mode
This commit is contained in:
45
src/components/ThemeToggle.tsx
Normal file
45
src/components/ThemeToggle.tsx
Normal file
@@ -0,0 +1,45 @@
|
||||
'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 { theme, setTheme } = useTheme();
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
if (!mounted) {
|
||||
// 渲染一个占位符以避免布局偏移
|
||||
return <div className='w-10 h-10' />;
|
||||
}
|
||||
|
||||
const toggleTheme = () => {
|
||||
// 检查浏览器是否支持 View Transitions API
|
||||
if (!document.startViewTransition) {
|
||||
setTheme(theme === 'dark' ? 'light' : 'dark');
|
||||
return;
|
||||
}
|
||||
|
||||
document.startViewTransition(() => {
|
||||
setTheme(theme === 'dark' ? 'light' : 'dark');
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={toggleTheme}
|
||||
className='w-10 h-10 p-2 rounded-full flex items-center justify-center text-gray-600 hover:bg-gray-200/50 dark:text-gray-300 dark:hover:bg-gray-700/50 transition-colors'
|
||||
aria-label='Toggle theme'
|
||||
>
|
||||
{theme === 'dark' ? (
|
||||
<Sun className='w-full h-full' />
|
||||
) : (
|
||||
<Moon className='w-full h-full' />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user