mirror of
https://github.com/DefectingCat/DefectingCat.github.io
synced 2025-07-15 16:51:37 +00:00
add handle system theme
This commit is contained in:
@ -1,22 +1,41 @@
|
||||
import clsx from 'clsx';
|
||||
import useMounted from 'lib/hooks/use-mounted';
|
||||
import { useTheme } from 'next-themes';
|
||||
import { memo } from 'react';
|
||||
import { memo, useCallback, useEffect } from 'react';
|
||||
import { FiMoon, FiSun } from 'react-icons/fi';
|
||||
|
||||
const MEDIA = '(prefers-color-scheme: dark)';
|
||||
|
||||
const DarkModeBtn = () => {
|
||||
const { mounted } = useMounted();
|
||||
const { systemTheme, theme, setTheme } = useTheme();
|
||||
const currentTheme = theme === 'system' ? systemTheme : theme;
|
||||
const { theme, setTheme } = useTheme();
|
||||
const handleTheme = (type: 'latte' | 'mocha') => () => {
|
||||
// const map = {
|
||||
// light: 'latte',
|
||||
// dark: 'mocha',
|
||||
// };
|
||||
// document.body.className = map[type];
|
||||
setTheme(type);
|
||||
};
|
||||
|
||||
const handleMediaQuery = useCallback(
|
||||
(e: MediaQueryListEvent | MediaQueryList) => {
|
||||
const isDark = e.matches;
|
||||
if (isDark) {
|
||||
setTheme('mocha');
|
||||
} else {
|
||||
setTheme('latte');
|
||||
}
|
||||
},
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[],
|
||||
);
|
||||
// Always listen to System preference
|
||||
useEffect(() => {
|
||||
const media = window.matchMedia(MEDIA);
|
||||
|
||||
// Intentionally use deprecated listener methods to support iOS & old browsers
|
||||
media.addListener(handleMediaQuery);
|
||||
handleMediaQuery(media);
|
||||
|
||||
return () => media.removeListener(handleMediaQuery);
|
||||
}, [handleMediaQuery]);
|
||||
|
||||
if (!mounted) {
|
||||
return (
|
||||
<button>
|
||||
@ -32,7 +51,7 @@ const DarkModeBtn = () => {
|
||||
|
||||
return (
|
||||
<>
|
||||
{currentTheme === 'mocha' ? (
|
||||
{theme === 'mocha' ? (
|
||||
<button>
|
||||
<FiSun className="w-5 h-5" onClick={handleTheme('latte')} />
|
||||
</button>
|
||||
|
@ -13,8 +13,8 @@ export default function RUAThemeProvider({
|
||||
attribute="class"
|
||||
storageKey="rua-theme"
|
||||
themes={['latte', 'mocha']}
|
||||
enableSystem
|
||||
defaultTheme="system"
|
||||
enableSystem={false}
|
||||
defaultTheme="latte"
|
||||
>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
|
Reference in New Issue
Block a user