-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.tsx
60 lines (49 loc) · 1.69 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import React, { createContext, useState, useContext, useEffect, ReactNode, JSX } from 'react';
import { ConfigProvider, theme as antdTheme } from 'antd';
type ThemeMode = 'light' | 'dark';
interface ThemeContextType {
theme: ThemeMode;
toggleTheme: () => void;
}
const ThemeContext = createContext<ThemeContextType>({
theme: 'light',
toggleTheme: () => {},
});
export const useTheme = () => useContext(ThemeContext);
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const [theme, setTheme] = useState<ThemeMode>('light');
// Check for user's preferred theme on component mount
useEffect(() => {
const savedTheme = localStorage.getItem('theme') as ThemeMode;
if (savedTheme) {
setTheme(savedTheme);
} else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
setTheme('dark');
}
}, []);
// Update localStorage when theme changes
useEffect(() => {
localStorage.setItem('theme', theme);
// Add or remove dark class from document body
if (theme === 'dark') {
document.body.classList.add('dark-mode');
} else {
document.body.classList.remove('dark-mode');
}
}, [theme]);
const toggleTheme = () => {
setTheme(prevTheme => (prevTheme === 'light' ? 'dark' : 'light'));
};
return (
<ThemeContext.Provider value={{ theme, toggleTheme }}>
<ConfigProvider
theme={{
algorithm: theme === 'dark' ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
}}
>
{children}
</ConfigProvider>
</ThemeContext.Provider>
);
};
export const withTheme = (component: JSX.Element) => <ThemeProvider>{component}</ThemeProvider>;