2024-05-24 10:20:15 +00:00
|
|
|
'use client';
|
|
|
|
import { useTheme } from 'next-themes';
|
|
|
|
import { SunIcon, MoonIcon, MonitorIcon } from 'lucide-react';
|
|
|
|
import { useCallback, useEffect, useState } from 'react';
|
2024-05-28 02:48:58 +00:00
|
|
|
import { cn } from '@/lib/utils';
|
2024-06-02 06:49:53 +00:00
|
|
|
import { Select } from '../SettingsDialog';
|
2024-05-24 10:20:15 +00:00
|
|
|
|
|
|
|
type Theme = 'dark' | 'light' | 'system';
|
|
|
|
|
2024-06-02 06:49:53 +00:00
|
|
|
const ThemeSwitcher = ({ className }: { className?: string }) => {
|
2024-05-24 10:20:15 +00:00
|
|
|
const [mounted, setMounted] = useState(false);
|
|
|
|
|
|
|
|
const { theme, setTheme } = useTheme();
|
|
|
|
|
|
|
|
const isTheme = useCallback((t: Theme) => t === theme, [theme]);
|
|
|
|
|
|
|
|
const handleThemeSwitch = (theme: Theme) => {
|
|
|
|
setTheme(theme);
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setMounted(true);
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (isTheme('system')) {
|
|
|
|
const preferDarkScheme = window.matchMedia(
|
|
|
|
'(prefers-color-scheme: dark)',
|
|
|
|
);
|
|
|
|
|
|
|
|
const detectThemeChange = (event: MediaQueryListEvent) => {
|
|
|
|
const theme: Theme = event.matches ? 'dark' : 'light';
|
|
|
|
setTheme(theme);
|
|
|
|
};
|
|
|
|
|
|
|
|
preferDarkScheme.addEventListener('change', detectThemeChange);
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
preferDarkScheme.removeEventListener('change', detectThemeChange);
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}, [isTheme, setTheme, theme]);
|
|
|
|
|
|
|
|
// Avoid Hydration Mismatch
|
|
|
|
if (!mounted) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
2024-06-02 06:49:53 +00:00
|
|
|
return (
|
|
|
|
<Select
|
|
|
|
className={className}
|
|
|
|
value={theme}
|
|
|
|
onChange={(e) => handleThemeSwitch(e.target.value as Theme)}
|
|
|
|
options={[
|
|
|
|
{ value: 'light', label: 'Light' },
|
|
|
|
{ value: 'dark', label: 'Dark' }
|
|
|
|
]}
|
2024-05-24 10:20:15 +00:00
|
|
|
/>
|
|
|
|
);
|
2024-05-30 16:08:37 +00:00
|
|
|
};
|
2024-05-31 05:32:00 +00:00
|
|
|
|
|
|
|
export default ThemeSwitcher;
|