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(() => {
|
|
|
|
const body = document.body;
|
2022-03-12 03:27:56 +00:00
|
|
|
if (theme === 'dark') {
|
|
|
|
body.setAttribute('theme-mode', 'dark');
|
2022-02-20 11:51:55 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-03-12 03:27:56 +00:00
|
|
|
if (theme === 'light') {
|
|
|
|
body.setAttribute('theme-mode', 'light');
|
2022-02-20 11:51:55 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}, [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,
|
|
|
|
};
|
|
|
|
};
|