Spaces:
Running
Running
import { Moon, Sun } from "lucide-react"; | |
import { useEffect, useState } from "react"; | |
import { Button } from "@/components/ui/button"; | |
import { storage, STORAGE_KEYS } from "@/lib/storage"; | |
export function ModeToggle() { | |
const [theme, setTheme] = useState(() => { | |
// Use storage lib or default to system preference | |
const storedTheme = storage.get<string>(STORAGE_KEYS.THEME); | |
if (storedTheme) return storedTheme; | |
return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; | |
}); | |
useEffect(() => { | |
const root = window.document.documentElement; | |
if (theme === "dark") { | |
root.classList.add("dark"); | |
} else { | |
root.classList.remove("dark"); | |
} | |
storage.set(STORAGE_KEYS.THEME, theme); | |
}, [theme]); | |
const toggleTheme = () => { | |
setTheme(theme === "light" ? "dark" : "light"); | |
}; | |
return ( | |
<Button variant="outline" size="icon" onClick={toggleTheme} className="h-9 w-9"> | |
<Sun className="h-4 w-4 rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" /> | |
<Moon className="absolute h-4 w-4 rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" /> | |
<span className="sr-only">Toggle theme</span> | |
</Button> | |
); | |
} | |