gonets/FRONT/DEV/src/store/themeContext.tsx

78 lines
2.7 KiB
TypeScript
Raw Normal View History

2025-06-30 13:16:33 +05:00
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>
);
};