gonets/FRONT/DEV/src/store/themeContext.tsx
test ee350c1852
Some checks failed
ci/woodpecker/manual/woodpecker Pipeline failed
Добавление настроек и их функциональности
2025-07-04 15:07:41 +05:00

59 lines
No EOL
2 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';
import {useThemeSettings} from "../hooks/useSettings";
type ThemeContextType = {
theme: ThemName;
};
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 = useThemeSettings();
const [theme, setTheme] = useState<ThemName>(getInitialTheme);
useEffect(() => {
setTheme(getInitialTheme)
}, [getInitialTheme]);
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 }}>
<StyledTheme theme={{ ...currentTheme === themeNames[1] ? light : dark }}>
<GlobalStyle />
{children}
</StyledTheme>
</ThemeContext.Provider>
);
};