2025-06-09 10:17:12 +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';
|
2025-07-04 15:07:41 +05:00
|
|
|
import {useThemeSettings} from "../hooks/useSettings";
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
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];
|
|
|
|
|
|
2025-07-04 15:07:41 +05:00
|
|
|
const getInitialTheme = useThemeSettings();
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
const [theme, setTheme] = useState<ThemName>(getInitialTheme);
|
|
|
|
|
|
2025-07-04 15:07:41 +05:00
|
|
|
useEffect(() => {
|
|
|
|
|
setTheme(getInitialTheme)
|
|
|
|
|
}, [getInitialTheme]);
|
2025-06-09 10:17:12 +05:00
|
|
|
|
|
|
|
|
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 (
|
2025-07-04 15:07:41 +05:00
|
|
|
<ThemeContext.Provider value={{ theme }}>
|
|
|
|
|
<StyledTheme theme={{ ...currentTheme === themeNames[1] ? light : dark }}>
|
2025-06-09 10:17:12 +05:00
|
|
|
<GlobalStyle />
|
|
|
|
|
{children}
|
|
|
|
|
</StyledTheme>
|
|
|
|
|
</ThemeContext.Provider>
|
|
|
|
|
);
|
|
|
|
|
};
|