2022-03-14 13:18:11 +00:00
|
|
|
import { useEffect, useState } from 'react';
|
|
|
|
import { LocalStorage } from '@vegaprotocol/react-helpers';
|
2022-03-11 00:28:48 +00:00
|
|
|
|
2022-03-14 13:18:11 +00:00
|
|
|
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());
|
2022-03-11 00:28:48 +00:00
|
|
|
useEffect(() => {
|
2022-03-14 13:18:11 +00:00
|
|
|
if (theme === darkTheme) {
|
|
|
|
document.documentElement.classList.add(darkThemeCssClass);
|
2022-03-11 00:28:48 +00:00
|
|
|
} else {
|
2022-03-14 13:18:11 +00:00
|
|
|
document.documentElement.classList.remove(darkThemeCssClass);
|
2022-03-11 00:28:48 +00:00
|
|
|
}
|
2022-03-14 13:18:11 +00:00
|
|
|
}, [theme]);
|
|
|
|
return [theme, () => setTheme(toggleTheme)];
|
2022-03-11 00:28:48 +00:00
|
|
|
}
|