File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed
gs/frontend/mcc/src/contexts Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change 1+ import { createContext , useContext , useEffect , useState } from "react" ;
2+
3+ type Theme = "light" | "dark" ;
4+
5+ interface ThemeContextType {
6+ theme : Theme ;
7+ toggleTheme : ( ) => void ;
8+ }
9+
10+ const ThemeContext = createContext < ThemeContextType | undefined > ( undefined ) ;
11+
12+ export function ThemeProvider ( { children } : { children : React . ReactNode } ) {
13+
14+ const [ theme , setTheme ] = useState < Theme > ( ( ) => {
15+ const stored = localStorage . getItem ( "theme" ) as Theme | null ;
16+ if ( stored ) return stored ;
17+
18+
19+ if ( window . matchMedia ( "(prefers-color-scheme: dark)" ) . matches ) { // Find system Preference
20+ return "dark" ;
21+ }
22+ return "light" ;
23+ } ) ;
24+
25+
26+ useEffect ( ( ) => {
27+ const root = document . documentElement ;
28+ if ( theme === "dark" ) {
29+ root . classList . add ( "dark" ) ;
30+ } else {
31+ root . classList . remove ( "dark" ) ;
32+ }
33+ localStorage . setItem ( "theme" , theme ) ;
34+ } , [ theme ] ) ;
35+
36+ const toggleTheme = ( ) => {
37+ setTheme ( ( prev ) => ( prev === "light" ? "dark" : "light" ) ) ;
38+ } ;
39+
40+ return (
41+ < ThemeContext . Provider value = { { theme, toggleTheme } } >
42+ { children }
43+ </ ThemeContext . Provider >
44+ ) ;
45+ }
46+
47+ export function useTheme ( ) {
48+ const context = useContext ( ThemeContext ) ;
49+ if ( ! context ) {
50+ throw new Error ( "useTheme must be used within ThemeProvider" ) ;
51+ }
52+ return context ;
53+ }
You can’t perform that action at this time.
0 commit comments