2024-12-10 10:42:04 +07:00
|
|
|
import React, { createContext, useContext, useEffect, useState } from 'react';
|
2024-11-06 11:13:04 +08:00
|
|
|
|
2024-12-17 16:32:17 +08:00
|
|
|
type Theme = 'dark' | 'light' | 'system';
|
2024-11-06 11:13:04 +08:00
|
|
|
|
|
|
|
type ThemeProviderProps = {
|
|
|
|
children: React.ReactNode;
|
|
|
|
defaultTheme?: Theme;
|
|
|
|
storageKey?: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
type ThemeProviderState = {
|
|
|
|
theme: Theme;
|
|
|
|
setTheme: (theme: Theme) => void;
|
|
|
|
};
|
|
|
|
|
|
|
|
const initialState: ThemeProviderState = {
|
2024-12-10 10:42:04 +07:00
|
|
|
theme: 'light',
|
2024-11-06 11:13:04 +08:00
|
|
|
setTheme: () => null,
|
|
|
|
};
|
|
|
|
|
|
|
|
const ThemeProviderContext = createContext<ThemeProviderState>(initialState);
|
|
|
|
|
|
|
|
export function ThemeProvider({
|
|
|
|
children,
|
2024-12-10 10:42:04 +07:00
|
|
|
defaultTheme = 'light',
|
2024-11-06 11:13:04 +08:00
|
|
|
storageKey = 'vite-ui-theme',
|
|
|
|
...props
|
|
|
|
}: ThemeProviderProps) {
|
|
|
|
const [theme, setTheme] = useState<Theme>(
|
|
|
|
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
|
|
|
|
);
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
const root = window.document.documentElement;
|
|
|
|
root.classList.remove('light', 'dark');
|
2024-12-10 10:42:04 +07:00
|
|
|
localStorage.setItem(storageKey, theme);
|
2024-11-06 11:13:04 +08:00
|
|
|
root.classList.add(theme);
|
2024-12-10 10:42:04 +07:00
|
|
|
}, [storageKey, theme]);
|
2024-11-06 11:13:04 +08:00
|
|
|
|
|
|
|
return (
|
2024-12-10 10:42:04 +07:00
|
|
|
<ThemeProviderContext.Provider
|
|
|
|
{...props}
|
|
|
|
value={{
|
|
|
|
theme,
|
|
|
|
setTheme,
|
|
|
|
}}
|
|
|
|
>
|
2024-11-06 11:13:04 +08:00
|
|
|
{children}
|
|
|
|
</ThemeProviderContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export const useTheme = () => {
|
|
|
|
const context = useContext(ThemeProviderContext);
|
|
|
|
|
|
|
|
if (context === undefined)
|
|
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
|
|
|
|
|
|
|
return context;
|
|
|
|
};
|
2024-12-17 11:23:00 +08:00
|
|
|
|
|
|
|
export const useIsDarkTheme = () => {
|
|
|
|
const { theme } = useTheme();
|
|
|
|
|
|
|
|
return theme === 'dark';
|
|
|
|
};
|