Files
auv/src/components/ThemeToggle.tsx
T

61 lines
1.9 KiB
TypeScript

import { useState, useRef, useEffect } from "react";
import { Sun, Moon, Monitor } from "lucide-react";
import { useTheme } from "../lib/use-theme";
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
const [expanded, setExpanded] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!expanded) return;
const handler = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) {
setExpanded(false);
}
};
document.addEventListener("mousedown", handler);
return () => document.removeEventListener("mousedown", handler);
}, [expanded]);
const options = [
{ value: "light" as const, icon: Sun, label: "浅色" },
{ value: "dark" as const, icon: Moon, label: "深色" },
{ value: "system" as const, icon: Monitor, label: "自动" },
];
if (!expanded) {
const CurrentIcon = options.find(o => o.value === theme)!.icon;
return (
<div ref={ref}>
<button
onClick={() => setExpanded(true)}
title="切换主题"
className="flex items-center justify-center w-8 h-8 rounded-lg bg-muted text-muted-foreground hover:text-foreground shadow-sm transition-colors"
>
<CurrentIcon className="h-4 w-4" />
</button>
</div>
);
}
return (
<div ref={ref} className="flex items-center bg-muted rounded-lg p-0.5 gap-0.5 shadow-sm">
{options.map(({ value, icon: Icon, label }) => (
<button
key={value}
onClick={() => { setTheme(value); setExpanded(false); }}
title={label}
className={`flex items-center justify-center w-8 h-8 rounded-md text-sm transition-colors ${
theme === value
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
}`}
>
<Icon className="h-4 w-4" />
</button>
))}
</div>
);
}