chore: transition animation for Sun and Moon icons when switching themes

This commit is contained in:
Sh1n3zZ 2025-04-29 21:21:39 +08:00
parent 34dfa05c9b
commit 2d2fe52bab
No known key found for this signature in database
GPG Key ID: 696702CF723B0452

View File

@ -106,46 +106,37 @@ export const useTheme = () => {
}; };
export function ModeToggle() { export function ModeToggle() {
const { theme, toggleTheme } = useTheme(); const { toggleTheme } = useTheme();
const [currentIconIndex, setCurrentIconIndex] = useState(0); const [systemMode, setSystemMode] = useState(false);
const icons = [
<Moon key="dark" className="h-[1.2rem] w-[1.2rem]" />,
<Sun key="light" className="h-[1.2rem] w-[1.2rem]" />,
<Monitor key="system" className="h-[1.2rem] w-[1.2rem]" />,
];
useEffect(() => { useEffect(() => {
const savedTheme = getTheme(); const currentTheme = getTheme();
const index = icons.findIndex(icon => icon.key === savedTheme); setSystemMode(currentTheme === "system");
setCurrentIconIndex(index >= 0 ? index : 0); }, []);
}, [theme]);
const handleClick = () => { const handleClick = () => {
toggleTheme?.(); toggleTheme?.();
const currentTheme = getTheme(); const newTheme = getTheme();
let nextTheme: Theme; setSystemMode(newTheme === "system");
if (currentTheme === "dark") {
nextTheme = "light";
} else if (currentTheme === "light") {
nextTheme = "system";
} else {
nextTheme = "dark";
}
const nextIndex = icons.findIndex(icon => icon.key === nextTheme);
setCurrentIconIndex(nextIndex >= 0 ? nextIndex : 0);
}; };
if (systemMode) {
return (
<Button variant="outline" size="icon" onClick={handleClick}>
<Monitor className="h-[1.2rem] w-[1.2rem]" />
</Button>
);
}
return ( return (
<Button <Button variant="outline" size="icon" onClick={handleClick}>
variant="outline" <Sun
size="icon" className={`relative dark:absolute h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0`}
onClick={handleClick} />
> <Moon
{icons[currentIconIndex]} className={`absolute dark:relative h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100`}
/>
</Button> </Button>
); );
} }