add new use rua theme hook

use new hook to handle theme switch
This commit is contained in:
DefectingCat
2023-11-10 14:46:36 +08:00
parent 50c3d1a945
commit f19c215386
3 changed files with 38 additions and 20 deletions

View File

@ -1,13 +1,13 @@
import { easings, useSpring } from '@react-spring/three';
import { useFrame, useLoader, useThree } from '@react-three/fiber';
import useRuaTheme from 'lib/hooks/use-rua-theme';
import { getMousePosition } from 'lib/utils';
import { useTheme } from 'next-themes';
import { useEffect, useRef } from 'react';
import useStore from 'store';
import * as THREE from 'three';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { rotationX, rotationY } from './home-model';
import useStore from 'store';
const CloudModel = () => {
const mixer = useRef<THREE.AnimationMixer | null>(null);
@ -16,14 +16,14 @@ const CloudModel = () => {
// After model loading, set theme to dark mode.
const restore = useRef(false);
const { theme, setTheme } = useTheme();
const { theme, handleTheme } = useRuaTheme();
// setDarkMode is async called by setTimeout, when component is unmounted
// it should not be called.
const setDarkMode = () => {
if (theme === 'mocha') return;
restore.current = true;
document.body.style.transition = 'all 1.2s ease-out';
setTheme('mocha');
handleTheme('mocha');
};
const [_, api] = useSpring(
{
@ -87,7 +87,7 @@ const CloudModel = () => {
window.removeEventListener('touchmove', moveHandler);
if (!restore.current) return;
setTheme('latte');
handleTheme('latte');
document.body.style.transition = 'all 0.3s ease-out';
};
// eslint-disable-next-line react-hooks/exhaustive-deps

View File

@ -1,23 +1,13 @@
import clsx from 'clsx';
import { MEDIA, THEME_MAP } from 'lib/consts';
import { MEDIA } from 'lib/consts';
import useMounted from 'lib/hooks/use-mounted';
import { useTheme } from 'next-themes';
import useRuaTheme from 'lib/hooks/use-rua-theme';
import { memo, useCallback, useEffect } from 'react';
import { FiMoon, FiSun } from 'react-icons/fi';
const DarkModeBtn = () => {
const { mounted } = useMounted();
const { theme, setTheme } = useTheme();
const handleTheme = (type: 'latte' | 'mocha') => () => {
const media = window.matchMedia(MEDIA);
const system = media.matches ? 'dark' : 'light';
setTheme(type);
if (THEME_MAP[system] === type) {
try {
window.localStorage.removeItem('rua-theme');
} catch (err) {}
}
};
const { theme, setTheme, handleTheme } = useRuaTheme();
const handleMediaQuery = useCallback(
(e: MediaQueryListEvent | MediaQueryList) => {
@ -64,11 +54,11 @@ const DarkModeBtn = () => {
<>
{theme === 'mocha' ? (
<button>
<FiSun className="w-5 h-5" onClick={handleTheme('latte')} />
<FiSun className="w-5 h-5" onClick={() => handleTheme('latte')} />
</button>
) : (
<button>
<FiMoon className="w-5 h-5" onClick={handleTheme('mocha')} />
<FiMoon className="w-5 h-5" onClick={() => handleTheme('mocha')} />
</button>
)}
</>