umami/hooks/useTheme.js

28 lines
716 B
JavaScript
Raw Normal View History

import { useEffect } from 'react';
import useStore, { setTheme } from 'store/app';
2020-09-20 08:33:39 +00:00
import { getItem, setItem } from 'lib/web';
import { THEME_CONFIG } from 'lib/constants';
const selector = state => state.theme;
2020-09-20 08:33:39 +00:00
2020-09-30 23:27:27 +00:00
export default function useTheme() {
2021-04-28 09:12:17 +00:00
const defaultTheme =
2021-04-28 09:18:54 +00:00
typeof window !== 'undefined'
? window?.matchMedia('(prefers-color-scheme: dark)')?.matches
2021-04-28 09:12:17 +00:00
? 'dark'
: 'light'
: 'light';
const theme = useStore(selector) || getItem(THEME_CONFIG) || defaultTheme;
2020-09-20 08:33:39 +00:00
function saveTheme(value) {
setItem(THEME_CONFIG, value);
setTheme(value);
2020-09-20 08:33:39 +00:00
}
useEffect(() => {
document.body.setAttribute('data-theme', theme);
}, [theme]);
return [theme, saveTheme];
}