vega-frontend-monorepo/apps/trading/hooks/use-theme-switcher.ts
Bartłomiej Głownia 8a829964be
Feature/38 data grid component (#77)
* Add ag-grid

* Add lazy loaded ag-grid component

* Add theme context, move VegaWallet to separate lib

* Fix trading app cypress configuration

* Lazy load ag-grid theme css files

* Encapsulate theme switch hook
2022-03-14 14:18:11 +01:00

42 lines
1.1 KiB
TypeScript

import { useEffect, useState } from 'react';
import { LocalStorage } from '@vegaprotocol/react-helpers';
const darkTheme = 'dark';
const lightTheme = 'light';
type themeVariant = typeof darkTheme | typeof lightTheme;
const darkThemeCssClass = darkTheme;
const getCurrentTheme = () => {
const theme = LocalStorage.getItem('theme');
if (
theme === darkTheme ||
(!theme &&
typeof window !== 'undefined' &&
window.matchMedia('(prefers-color-scheme: dark)').matches)
) {
return darkTheme;
}
return lightTheme;
};
const toggleTheme = () => {
const theme = document.documentElement.classList.contains(darkThemeCssClass)
? lightTheme
: darkTheme;
LocalStorage.setItem('theme', theme);
return theme;
};
export function useThemeSwitcher(): [themeVariant, () => void] {
const [theme, setTheme] = useState<themeVariant>(getCurrentTheme());
useEffect(() => {
if (theme === darkTheme) {
document.documentElement.classList.add(darkThemeCssClass);
} else {
document.documentElement.classList.remove(darkThemeCssClass);
}
}, [theme]);
return [theme, () => setTheme(toggleTheme)];
}