78 lines
No EOL
2.7 KiB
TypeScript
78 lines
No EOL
2.7 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect } from 'react';
|
|
import { ThemeProvider as StyledTheme } from 'styled-components';
|
|
import { light, dark} from '../const/theme/theme';
|
|
import { GlobalStyle } from '../const/theme/globalStyles';
|
|
import { themeNames, ThemName } from '../const/theme/names';
|
|
|
|
type ThemeContextType = {
|
|
theme: ThemName;
|
|
toggleTheme: () => void;
|
|
};
|
|
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
export const useTheme = () => {
|
|
const context = useContext(ThemeContext);
|
|
if (!context) {
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
|
}
|
|
return context;
|
|
};
|
|
|
|
export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
|
const getSystemTheme = () =>
|
|
window.matchMedia('(prefers-color-scheme: dark)').matches ? themeNames[2] : themeNames[1];
|
|
|
|
const getInitialTheme = () => {
|
|
let savedTheme = localStorage.getItem('theme') as ThemName;
|
|
if (!savedTheme) {
|
|
savedTheme = themeNames[3]; // Устанавливаем значение по умолчанию
|
|
localStorage.setItem('theme', savedTheme); // Сохраняем без JSON.stringify
|
|
}
|
|
return savedTheme;
|
|
};
|
|
|
|
const [theme, setTheme] = useState<ThemName>(getInitialTheme);
|
|
|
|
const toggleTheme = () => {
|
|
setTheme((prev) => {
|
|
let newTheme: ThemName;
|
|
if (prev === themeNames[3]) {
|
|
newTheme = themeNames[1];
|
|
} else if (prev === themeNames[1]) {
|
|
newTheme = themeNames[2];
|
|
} else {
|
|
newTheme = themeNames[3];
|
|
}
|
|
localStorage.setItem('theme', newTheme);
|
|
|
|
return newTheme;
|
|
});
|
|
};
|
|
|
|
useEffect(() => {
|
|
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
|
|
let currentTheme = localStorage.getItem('theme')
|
|
const handleChange = () => {
|
|
if (currentTheme === themeNames[3]) {
|
|
const newTheme = getSystemTheme();
|
|
|
|
setTheme(newTheme);
|
|
localStorage.setItem('theme', themeNames[3]);
|
|
}
|
|
};
|
|
mediaQuery.addEventListener('change', handleChange);
|
|
return () => mediaQuery.removeEventListener('change', handleChange);
|
|
}, [theme]);
|
|
|
|
const currentTheme = theme === themeNames[3] ? getSystemTheme() : theme;
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
|
<StyledTheme theme={{ ...currentTheme === themeNames[1] ? light : dark, toggleTheme }}>
|
|
<GlobalStyle />
|
|
{children}
|
|
</StyledTheme>
|
|
</ThemeContext.Provider>
|
|
);
|
|
}; |