umami/hooks/useTheme.js

37 lines
925 B
JavaScript
Raw Normal View History

import { useEffect } from 'react';
import useStore, { setTheme } from 'store/app';
2022-08-29 05:20:54 +02:00
import { getItem, setItem } from 'next-basics';
2020-09-20 10:33:39 +02:00
import { THEME_CONFIG } from 'lib/constants';
const selector = state => state.theme;
2020-09-20 10:33:39 +02:00
2020-10-01 01:27:27 +02:00
export default function useTheme() {
2021-04-28 11:12:17 +02:00
const defaultTheme =
2021-04-28 11:18:54 +02:00
typeof window !== 'undefined'
? window?.matchMedia('(prefers-color-scheme: dark)')?.matches
2021-04-28 11:12:17 +02:00
? 'dark'
: 'light'
: 'light';
const theme = useStore(selector) || getItem(THEME_CONFIG) || defaultTheme;
2020-09-20 10:33:39 +02:00
function saveTheme(value) {
setItem(THEME_CONFIG, value);
setTheme(value);
2020-09-20 10:33:39 +02:00
}
useEffect(() => {
document.body.setAttribute('data-theme', theme);
}, [theme]);
useEffect(() => {
2023-02-15 11:27:18 +01:00
const url = new URL(window?.location?.href);
const theme = url.searchParams.get('theme');
if (['light', 'dark'].includes(theme)) {
saveTheme(theme);
}
}, []);
2020-09-20 10:33:39 +02:00
return [theme, saveTheme];
}