mirror of
https://github.com/arthur-pbty/chrono.git
synced 2026-06-03 15:07:21 +02:00
60 lines
1.4 KiB
TypeScript
60 lines
1.4 KiB
TypeScript
"use client";
|
|
|
|
import React, { createContext, useContext, useEffect, useState } from "react";
|
|
|
|
type Theme = "light" | "dark";
|
|
|
|
interface ThemeContextType {
|
|
theme: Theme;
|
|
toggleTheme: () => void;
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeContextType>({
|
|
theme: "dark",
|
|
toggleTheme: () => {},
|
|
});
|
|
|
|
export function useTheme() {
|
|
return useContext(ThemeContext);
|
|
}
|
|
|
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
|
const [theme, setTheme] = useState<Theme>("dark");
|
|
const [mounted, setMounted] = useState(false);
|
|
|
|
useEffect(() => {
|
|
const stored = localStorage.getItem("chrono-theme") as Theme | null;
|
|
if (stored) {
|
|
setTheme(stored);
|
|
} else if (window.matchMedia("(prefers-color-scheme: light)").matches) {
|
|
setTheme("light");
|
|
}
|
|
setMounted(true);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
if (!mounted) return;
|
|
const root = document.documentElement;
|
|
if (theme === "dark") {
|
|
root.classList.add("dark");
|
|
} else {
|
|
root.classList.remove("dark");
|
|
}
|
|
localStorage.setItem("chrono-theme", theme);
|
|
}, [theme, mounted]);
|
|
|
|
const toggleTheme = () => {
|
|
setTheme((prev) => (prev === "dark" ? "light" : "dark"));
|
|
};
|
|
|
|
if (!mounted) {
|
|
return <div style={{ visibility: "hidden" }}>{children}</div>;
|
|
}
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
}
|