- Migrated from Python pre-commit to NodeJS-native solution - Reorganized documentation structure - Set up Husky + lint-staged for efficient pre-commit hooks - Fixed Dockerfile healthcheck issue - Added comprehensive documentation index
44 lines
1.3 KiB
TypeScript
44 lines
1.3 KiB
TypeScript
import { useEffect, useMemo } from 'react';
|
|
import { useLocalStorage } from './useLocalStorage';
|
|
|
|
type Theme = 'light' | 'dark' | 'system';
|
|
|
|
export function useTheme() {
|
|
const [theme, setTheme] = useLocalStorage<Theme>('theme', 'system');
|
|
|
|
const systemTheme = useMemo(() => {
|
|
if (typeof window !== 'undefined' && window.matchMedia) {
|
|
return window.matchMedia('(prefers-color-scheme: dark)').matches
|
|
? 'dark'
|
|
: 'light';
|
|
}
|
|
return 'light';
|
|
}, []);
|
|
|
|
const applyTheme = () => {
|
|
const themeToApply = theme === 'system' ? systemTheme : theme;
|
|
const root = window.document.documentElement;
|
|
root.classList.remove('light', 'dark');
|
|
root.classList.add(themeToApply);
|
|
};
|
|
|
|
useEffect(() => {
|
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
|
const handleChange = () => {
|
|
if (theme === 'system') {
|
|
applyTheme();
|
|
}
|
|
};
|
|
mediaQuery.addEventListener('change', handleChange);
|
|
return () => mediaQuery.removeEventListener('change', handleChange);
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [theme]);
|
|
|
|
useEffect(() => {
|
|
applyTheme();
|
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
}, [theme, systemTheme]);
|
|
|
|
return { theme, setTheme };
|
|
}
|