2022-03-12 03:27:56 +00:00
|
|
|
import { useEffect, useState } from 'react';
|
2022-02-20 11:51:55 +00:00
|
|
|
|
|
|
|
export enum Theme {
|
2022-03-12 03:27:56 +00:00
|
|
|
'dark' = 'dark',
|
|
|
|
'light' = 'light',
|
2022-02-20 11:51:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export const useTheme = () => {
|
|
|
|
const [theme, setTheme] = useState(Theme.light);
|
|
|
|
|
|
|
|
const toggle = () => {
|
2022-03-12 03:27:56 +00:00
|
|
|
const nextTheme = theme === 'dark' ? Theme.light : Theme.dark;
|
2022-02-20 11:51:55 +00:00
|
|
|
setTheme(nextTheme);
|
|
|
|
};
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-03-22 12:31:21 +00:00
|
|
|
// const body = document.body;
|
|
|
|
// if (theme === 'dark') {
|
|
|
|
// body.setAttribute('theme-mode', 'dark');
|
|
|
|
// return;
|
|
|
|
// }
|
|
|
|
// if (theme === 'light') {
|
|
|
|
// body.setAttribute('theme-mode', 'light');
|
|
|
|
// return;
|
|
|
|
// }
|
2022-02-20 11:51:55 +00:00
|
|
|
}, [theme]);
|
|
|
|
|
|
|
|
useEffect(() => {
|
2022-03-12 03:27:56 +00:00
|
|
|
const mql = window.matchMedia('(prefers-color-scheme: dark)');
|
2022-02-20 11:51:55 +00:00
|
|
|
|
|
|
|
function matchMode(e) {
|
|
|
|
if (e.matches) {
|
|
|
|
setTheme(Theme.dark);
|
|
|
|
} else {
|
|
|
|
setTheme(Theme.light);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
matchMode(mql);
|
2022-03-12 03:27:56 +00:00
|
|
|
mql.addEventListener('change', matchMode);
|
2022-02-20 11:51:55 +00:00
|
|
|
}, []);
|
|
|
|
|
|
|
|
return {
|
|
|
|
theme,
|
|
|
|
toggle,
|
|
|
|
};
|
|
|
|
};
|