index.tsx
1 import { ConfigProvider, theme } from "antd"; 2 import { createContext, PropsWithChildren, useEffect, useState } from "react"; 3 4 type ColorModeContextType = { 5 mode: string; 6 setMode: (mode: string) => void; 7 }; 8 9 export const ColorModeContext = createContext<ColorModeContextType>({} as ColorModeContextType); 10 11 export const ColorModeContextProvider = ({ children }: PropsWithChildren) => { 12 const colorModeFromLocalStorage = localStorage.getItem("colorMode"); 13 const isSystemPreferenceDark = window?.matchMedia("(prefers-color-scheme: dark)").matches; 14 15 const systemPreference = isSystemPreferenceDark ? "dark" : "light"; 16 const [mode, setMode] = useState(colorModeFromLocalStorage || systemPreference); 17 18 useEffect(() => { 19 window.localStorage.setItem("colorMode", mode); 20 }, [mode]); 21 22 const setColorMode = () => { 23 if (mode === "light") { 24 setMode("dark"); 25 } else { 26 setMode("light"); 27 } 28 }; 29 30 const { darkAlgorithm, defaultAlgorithm } = theme; 31 32 return ( 33 <ColorModeContext.Provider 34 value={{ 35 setMode: setColorMode, 36 mode, 37 }} 38 > 39 <ConfigProvider 40 // you can change the theme colors here. example: ...RefineThemes.Magenta, 41 theme={{ 42 algorithm: mode === "light" ? defaultAlgorithm : darkAlgorithm, 43 token: { 44 colorPrimary: "#dc7734", 45 }, 46 }} 47 > 48 {children} 49 </ConfigProvider> 50 </ColorModeContext.Provider> 51 ); 52 };