Initial commit: Complete NodeJS-native setup
- 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
This commit is contained in:
43
hooks/useTheme.ts
Normal file
43
hooks/useTheme.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
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 };
|
||||
}
|
||||
Reference in New Issue
Block a user