2023-07-25 00:20:37 +03:00
|
|
|
import { createContext, useContext, useEffect, useState } from 'react';
|
2023-07-15 17:46:19 +03:00
|
|
|
import useLocalStorage from '../hooks/useLocalStorage';
|
|
|
|
|
|
|
|
|
|
|
|
interface IThemeContext {
|
|
|
|
darkMode: boolean
|
2023-07-25 00:20:37 +03:00
|
|
|
noNavigation: boolean
|
2023-07-15 17:46:19 +03:00
|
|
|
toggleDarkMode: () => void
|
2023-07-25 00:20:37 +03:00
|
|
|
toggleNoNavigation: () => void
|
2023-07-15 17:46:19 +03:00
|
|
|
}
|
|
|
|
|
2023-07-25 00:20:37 +03:00
|
|
|
const ThemeContext = createContext<IThemeContext | null>(null);
|
|
|
|
export const useConceptTheme = () => {
|
|
|
|
const context = useContext(ThemeContext);
|
|
|
|
if (!context) {
|
|
|
|
throw new Error(
|
|
|
|
'useConceptTheme has to be used within <ThemeState.Provider>'
|
|
|
|
);
|
|
|
|
}
|
|
|
|
return context;
|
|
|
|
}
|
2023-07-15 17:46:19 +03:00
|
|
|
|
|
|
|
interface ThemeStateProps {
|
|
|
|
children: React.ReactNode
|
|
|
|
}
|
|
|
|
|
|
|
|
export const ThemeState = ({ children }: ThemeStateProps) => {
|
|
|
|
const [darkMode, setDarkMode] = useLocalStorage('darkMode', false);
|
2023-07-25 00:20:37 +03:00
|
|
|
const [noNavigation, setNoNavigation] = useState(false);
|
2023-07-15 17:46:19 +03:00
|
|
|
|
|
|
|
const setDarkClass = (isDark: boolean) => {
|
|
|
|
const root = window.document.documentElement;
|
|
|
|
if (isDark) {
|
|
|
|
root.classList.add('dark');
|
|
|
|
} else {
|
|
|
|
root.classList.remove('dark');
|
|
|
|
}
|
2023-07-20 17:11:03 +03:00
|
|
|
root.setAttribute('data-color-scheme', !isDark ? 'light' : 'dark');
|
2023-07-15 17:46:19 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setDarkClass(darkMode)
|
|
|
|
}, [darkMode]);
|
|
|
|
|
|
|
|
return (
|
|
|
|
<ThemeContext.Provider value={{
|
2023-07-25 00:20:37 +03:00
|
|
|
darkMode, toggleDarkMode: () => setDarkMode(prev => !prev),
|
|
|
|
noNavigation, toggleNoNavigation: () => setNoNavigation(prev => !prev),
|
2023-07-15 17:46:19 +03:00
|
|
|
}}>
|
|
|
|
{children}
|
|
|
|
</ThemeContext.Provider>
|
|
|
|
);
|
2023-07-25 00:20:37 +03:00
|
|
|
}
|