mirror of
https://github.com/hanzoai/cd-ui.git
synced 2026-10-30 20:42:45 +00:00
Signed-off-by: Bernhard Schaidhammer <[email protected]>
48 lines
1.1 KiB
TypeScript
48 lines
1.1 KiB
TypeScript
import * as React from 'react';
|
|
|
|
export const THEME_KEY = 'theme';
|
|
|
|
export enum Theme {
|
|
Dark = 'dark',
|
|
Light = 'light',
|
|
}
|
|
|
|
const parseTheme = (): Theme => {
|
|
try {
|
|
const stored = JSON.parse(window.localStorage.getItem(THEME_KEY));
|
|
if (stored === Theme.Dark || stored === Theme.Light) {
|
|
return stored;
|
|
}
|
|
} catch {
|
|
// ignore invalid JSON or missing key
|
|
}
|
|
return Theme.Light;
|
|
};
|
|
|
|
const init = parseTheme();
|
|
|
|
interface ThemeContextProps {
|
|
theme: Theme;
|
|
set: (th: Theme) => void;
|
|
}
|
|
|
|
export const ThemeContext = React.createContext({theme: init} as ThemeContextProps);
|
|
|
|
export const ThemeProvider = (props: {children: React.ReactNode}) => {
|
|
const [theme, setTheme] = React.useState(init);
|
|
React.useEffect(() => {
|
|
window.localStorage.setItem(THEME_KEY, JSON.stringify(theme));
|
|
}, [theme]);
|
|
|
|
return <ThemeContext.Provider value={{theme, set: (th) => setTheme(th)}}>{props.children}</ThemeContext.Provider>;
|
|
};
|
|
|
|
export const useTheme = () => {
|
|
try {
|
|
const dmCtx = React.useContext(ThemeContext);
|
|
return dmCtx.theme;
|
|
} catch {
|
|
return Theme.Light;
|
|
}
|
|
};
|